我已经使用挂钩向WordPress图像上传程序添加了一些自定义字段attachment_fields_to_edit
和attachment_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>\';
}
}
最合适的回答,由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 ] );
}