here:
What you need is to create a meta box so first you use the add_meta_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' );
}
here you can see that i used “events” as the post type i want to register this meta box to and that my callback function is: Businesses_custom_metabox()
and its the function that actually displays the metabox, so we define it like this:
/**
* 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;
}
I tried to comment ever bit of it so you can understand better.
And the last thing you have to do is process the metabox when a post is saved:
//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);
}
}
}