这里:您需要创建一个元框,因此首先使用add\\u meta\\u box()
// Hook into WordPress add_meta_boxes action
add_action( \'add_meta_boxes\', \'add_Businesses_custom_metabox\' );
/**
* Add meta box function
*/
function add_Businesses_custom_metabox() {
add_meta_box( \'custom-metabox\', __( \'Businesses\' ), \'Businesses_custom_metabox\', \'events\', \'side\', \'high\' );
}
在这里,您可以看到,我使用“事件”作为我要注册此元框的post类型,我的回调函数是:
Businesses_custom_metabox()
它是实际显示metabox的函数,因此我们对其进行如下定义:
/**
* Display the metabox
*/
function Businesses_custom_metabox($post) {
global $post,$current_user;
//remember the current $post object
$real_post = $post;
//get curent user info (we need the ID)
get_currentuserinfo();
//create nonce
echo \'<input type="hidden" name="Businesses_meta_box_nonce" value="\', wp_create_nonce(basename(__FILE__)), \'" />\';
//get saved meta
$selected = get_post_meta( $post->ID, \'a_businesses\', true );
//create a query for all of the user businesses posts
$Businesses_query = new WP_Query();
$Businesses_query->query(array(
\'post_type\' => \'posts\',
\'posts_per_page\' => -1,
\'author\' => $current_user->ID));
if ($Businesses_query->have_posts()){
echo \'<select name="a_businesses" id="a_businesses">\';
//loop over all post and add them to the select dropdown
while ($Businesses_query->have_posts()){
$Businesses_query->the_post();
echo \'<option value="\'.$post->ID.\'" \';
if ( $post->ID == $selected){
echo \'selected="selected"\';
}
echo \'>\'.$post->post_title .\'</option>\';
}
echo \'<select>\';
}
//reset the query and the $post to its real value
wp_reset_query();
$post = $real_post;
}
我试着对其中的任何一点进行评论,以便你能更好地理解。最后一件事是在保存帖子时处理元盒:
//hook to save the post meta
add_action( \'save_post\', \'save_Businesses_custom_metabox\' );
/**
* Process the custom metabox fields
*/
function save_Businesses_custom_metabox( $post_id ) {
global $post;
// verify nonce
if (!wp_verify_nonce($_POST[\'Businesses_meta_box_nonce\'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) {
return $post_id;
}
// check permissions
if (\'events\' == $_POST[\'post_type\']) {
if (!current_user_can(\'edit_page\', $post_id)) {
return $post_id;
}
} elseif (!current_user_can(\'edit_post\', $post_id)) {
return $post_id;
}
if( $_POST ) {
$old = get_post_meta($post_id, \'a_businesses\', true);
$new = $_POST[\'a_businesses\'];
if ($new && $new != $old){
update_post_meta($post_id, \'a_businesses\', $new);
}
}
}