我已将自定义元框添加到自定义帖子类型中,但它不会在单击发布或更新按钮时保存内容。
/*
* Custom book metabox
*/
// Add metabox
function author_book_meta_box_add() {
add_meta_box( \'author-book\', \'Select Book of Author\', \'author_book_meta_box\', \'awp-author\', \'normal\', \'high\' );
}
add_action( \'add_meta_boxes\', \'author_book_meta_box_add\' );
// Metabox callback
function author_book_meta_box( $post ) {
$values = get_post_custom($post->ID);
//testing...
print_r($values);
$selected = isset( $values[\'book_meta_box_select\'] ) ? esc_attr( $values[\'book_meta_box_select\'][0] ) : \'\';
echo "selected".$selected;
// Add a nonce field so we can check for it later.
//wp_nonce_field( \'author_book_meta_box_save\', \'author_book_meta_box_nonce\' );
?>
<p>
<label for="book_meta_box_select">Select Book: </label>
<select name=\'book_meta_box_select\'>
<?php $posts=get_posts(array(\'post_type\' => \'awp-catalogue\', \'posts_per_page\' => -1)); foreach ($posts as $post): ?>
<option value="<?php echo esc_attr($post->post_title); ?>" <?php selected( $selected, $post->post_title ); ?>><?php echo esc_html($post->post_title); ?></option>
<?php endforeach; ?>
</select>
</p>
<?php
}
function author_book_meta_box_save( $post_id )
{
// Bail if we\'re doing an auto save
if( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
// if our nonce isn\'t there, or we can\'t verify it, bail
if( !isset( $_POST[\'meta_box_nonce\'] ) || !wp_verify_nonce( $_POST[\'meta_box_nonce\'], \'author_book_meta_box_nonce\' ) ) return;
// if our current user can\'t edit this post, bail
if( !current_user_can( \'edit_post\' ) ) return;
// Make sure your data is set before trying to save it
if( isset( $_POST[\'book_meta_box_select\'] ) )
update_post_meta( $post_id, \'book_meta_box_select\', esc_attr( $_POST[\'book_meta_box_select\'] ) );
}
add_action( \'save_post\', \'author_book_meta_box_save\' );