值为空时不更新自定义字段

时间:2011-10-15 作者:laras126

我已经使用挂钩向WordPress图像上传程序添加了一些自定义字段attachment_fields_to_editattachment_fields_to_save. 除了用户删除字段外,所有操作都很好。例如,该字段过去常说“油画”,用户将其删除,希望该字段为空白,但该字段仍然说“油画”。但是,将文本更改为其他内容效果很好。你知道为什么会这样吗?提前感谢

这是我的代码:

// Add custom fields to the media uploader
function wpf_fields_edit( $form_fields, $post ) {
    $post->post_type == \'attachment\';
    $form_fields[ \'wpf_g_medium\' ] = array(
        \'label\' => __( \'Medium\' ),
        \'input\' => \'text\',
        \'value\' => get_post_meta( $post->ID, \'_wpf_g_medium\', true )
    );
    $form_fields[ \'wpf_g_medium\' ][ \'label\' ] = __( \'Medium\' );
    $form_fields[ \'wpf_g_medium\' ][ \'input\' ] = \'text\';
    $form_fields[ \'wpf_g_medium\' ][ \'value\' ] = get_post_meta( $post->ID, \'_wpf_g_medium\', true );

    // A couple more fields are added here, using the same code

    return $form_fields;
}    
add_filter( \'attachment_fields_to_edit\', \'wpf_fields_edit\', NULL, 2 );

// Save the fields\' data
function wpf_fields_save( $post, $attachment ) {
    $fields = array(\'wpf_g_medium\', \'wpf_g_dimen\', \'wpf_g_collabs\');
    foreach( $fields as $field ) {
        $key = \'_\' . $field;
        if( isset( $attachment[ $field ] ) ) {
            if( trim( $attachment[ $field ] ) == \'\' ) $post[ \'errors\' ][ $field ][ \'errors\' ][] = __( \'Error! Something went wrong.\' );
            else update_post_meta( $post[ \'ID\' ], $key, $attachment[ $field ] );
        }    
    }
    return $post;
}     
add_filter( \'attachment_fields_to_save\', \'wpf_fields_save\', NULL, 2 );

// Print the values, called in attachment.php
function get_artwork_fields_info() {
    global $post;
    $fields = array(\'wpf_g_medium\', \'wpf_g_dimen\', \'wpf_g_collabs\');
    $title = $post->post_title;

    if( $fields ) {
        echo \'<ul id="artwork-meta"><li><em>\' . $title . \'</em></li>\';
        foreach ( $fields as $field ) {
            $key = \'_\' . $field;
            $meta =  get_post_meta( $post->ID, $key, true );
            if ( $meta ) {
                echo \'<li>\';
                echo $meta;
                echo \'</li>\';
            }
       }
       echo \'</ul>\';
    }
}

1 个回复
最合适的回答,由SO网友:chifliiiii 整理而成

您正在检查字段是否为空。如果它也是空的,请尝试更新它

 if( trim( $attachment[ $field ] ) == \'\' ) $post[ \'errors\' ][ $field ][ \'errors\' ][] = __( \'Error! Something went wrong.\' );
 else update_post_meta( $post[ \'ID\' ], $key, $attachment[ $field ] );
试试看

if( isset( $attachment[ $field ] ) ) {
            if( trim( $attachment[ $field ] ) == \'\' )
            $post[ \'errors\' ][ $field ][ \'errors\' ][] = __( \'Error! Something went wrong.\' );
            endif;
            update_post_meta( $post[ \'ID\' ], $key, $attachment[ $field ] );
        } 

结束

相关推荐

how to edit attachments?

在将例如文件附加到帖子时,如何在事后编辑/删除它们?在帖子编辑器中找不到任何内容。谢谢