您的上述代码应按原样工作。
但是,在保存函数的末尾有一个逻辑错误-您使两个字段的保存取决于$_POST[\'_url\']
已设置
我想这不是故意的。您可能需要以下内容:
if ( isset( $_POST[\'_url\'] ) ) {
update_post_meta( $post_id, \'_url\', $_POST[\'_url\'] );
} else {
delete_post_meta( $post_id, \'_url\' );
}
if ( isset($_POST[\'_testimonial\'] ) ) {
update_post_meta( $post_id, \'_testimonial\', $_POST[\'_testimonial\'] );
} else {
delete_post_meta( $post_id, \'_testimonial\' );
}
虽然上述功能可能是您正在寻找的功能,但如果要保存(或创建)两个以上的自定义字段,则效率不高,因此我建议您执行以下操作:
class WPSE_95952_meta
{
private $fields = array(
array(
\'name\' => \'_url\',
\'label\' => \'URL\'
),
array(
\'name\' => \'_testimonial\',
\'label\' => \'Testimonial\'
)
);
public function __construct()
{
// add a meta box for WordPress \'project\' type
add_action( \'add_meta_boxes\', array( $this, \'add_project_box\' ) );
// add a callback function to save any data a user enters in
add_action( \'save_post\', array( $this, \'portfolio_meta_save\' ) );
}
public function add_project_box()
{
add_meta_box(
\'portfolio_meta\',
\'Project Infos\',
array( $this, \'portfolio_meta_setup\' ),
\'project\',
\'side\',
\'low\'
);
}
public function portfolio_meta_setup()
{
global $post;
$output = \'<div class="portfolio_meta_control">\';
foreach ( $this->fields as $field ) {
$output .= \'<label>\' . $field[\'label\'] . \'</label>\' .
\'<p>\' .
\'<input type="text" name="\' . $field[\'name\'] .
\'" value="\' . get_post_meta( $post->ID, $field[\'name\'], true ) .
\'" style="width: 100%;" />\' .
\'</p>\';
}
$output .= \'</div>\';
// create for validation
$output .= \'<input type="hidden" name="meta_noncename" value="\' .
wp_create_nonce(__FILE__) . \'" />\';
echo $output;
}
public function portfolio_meta_save( $post_id )
{
// exit on autosave
if ( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE ) {
return $post_id;
}
// check nonce
if (
! isset( $_POST[\'meta_noncename\'] ) ||
! wp_verify_nonce( $_POST[\'meta_noncename\'], __FILE__ )
) {
return $post_id;
}
// check capabilities
if (
( \'post\' === $_POST[\'post_type\'] && ! current_user_can( \'edit_post\', $post_id ) ) ||
! current_user_can( \'edit_page\', $post_id )
) {
return $post_id;
}
foreach ( $this->fields as $field ) {
$old = get_post_meta( $post_id, $field[\'name\'], true );
$new = isset( $_POST[$field[\'name\']] ) ? $_POST[$field[\'name\']] : false;
if ( $new && $new != $old ) {
update_post_meta( $post_id, $field[\'name\'], $new );
} elseif ( ! $new && $old ) {
delete_post_meta( $post_id, $field[\'name\'], $old );
}
}
}
}
$wpse_95952_meta = new WPSE_95952_meta();