如果字段存在,请选择下一个字段

时间:2014-03-05 13:05:57

标签: php wordpress loops foreach

我正在使用Wordpress中的小型自定义管理员,用户可以上传5张图片。

我将图片上传到Wordpress库,然后将图片网址保存在帖子的自定义字段中。

我想制作一些内容,如果用户上传图片,例如第一个和第二个字段已经存储了一个图片网址,则脚本会占用下一个字段。

我现在有这个,但它不起作用:

在此脚本之前,我有文件上传,此脚本仅适用于表单提交。

使用current_user_company()我会收到用户帖子的ID。 (这是一个定制的功能)

$company_images = range( 0, 6 );
unset( $company_images[0] );


    $field = 1;
    foreach ( $company_images as $key => $value ) {
        if( get_post_meta( current_user_company( 'ID' ), 'company_image_' . $field, true ) ) {
            $field++;
            $image_field = update_post_meta( current_user_company( 'ID' ), 'company_image_' . $field, $attachment_url );
        }
    }

1 个答案:

答案 0 :(得分:0)

您只检查一个字段,即:

如果用户已经使用过字段1-3,那么您需要使用4,所以在您的代码中:

$field = 1;
foreach ( $company_images as $key => $value ) {
    //this while loop will iterate through every used field        
    while( get_post_meta( current_user_company( 'ID' ), 'company_image_' . $field, true ) ) 
        $field++;
    //when the program reaches this point, $field should be 4 in our example 
    $image_field = update_post_meta( current_user_company( 'ID' ), 'company_image_' . $field, $attachment_url );
    break;
}