I want to create a dropdown box that populates from my Contacts
custom post type that I created. In my Contacts
post I also created a meta box called Phone
which stores a phone number.
What I want to do is, i.e. the contact John
was chose from the dropdown box, there will be a box right next to it and automatically grab the phone number from John's
meta box fill the box with the phone number.
I'm little lost on how to do this, appreciated if someone could help me with this. Thanks!
p.s. I'm using Bootstrap so I could use its dropdown.
Custom Post Type:
add_action( 'init', array(&$this, 'contacts_post_type'));
function contacts_post_type() {
$labels = array(
'name' => __( 'Contacts' ),
'singular_name' => __( 'Contact' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Contact' ),
'edit_item' => __( 'Edit Contact' ),
'new_item' => __( 'New Contact' ),
'all_items' => __( 'All Contacts' ),
'view_item' => __( 'View Contact' ),
'search_items' => __( 'Search Contacts' ),
'not_found' => __( 'No contacts found' ),
'not_found_in_trash' => __( 'No contacts found in the Trash' ),
'menu_name' => 'Contacts'
);
$args = array(
'labels' => $labels,
'description' => 'List of contacts',
'public' => false,
'show_in_menu' => true,
'show_ui' => true,
'supports' => array( 'title', 'editor' ),
'has_archive' => true,
);
register_post_type( 'contacts', $args );
}
Meta Box:
add_action( 'add_meta_boxes', array(&$this, 'add_number_metaboxes'));
add_action( 'save_post', array(&$this, 'wpt_save_number_meta'), 1, 2);
function add_number_metaboxes() {
add_meta_box('wpt_number_location', 'Phone Number', array(&$this, 'wpt_number_location'), 'contacts', 'normal', 'default');
}
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the location data if its already been entered
$location = get_post_meta($post->ID, '_location', true);
// Echo out the field
echo '<input type="text" name="_location" value="' . $location . '" class="widefat" />';
}
function wpt_save_number_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
$number_meta['_location'] = $_POST['_location'];
// Add values of $number_meta as custom fields
foreach ($number_meta as $key => $value) {
if ( $post->post_type == 'revision' ) {
return;
}
$value = implode(',', (array)$value);
if (get_post_meta($post->ID, $key, FALSE)) {
update_post_meta($post->ID, $key, $value);
} else {
add_post_meta($post->ID, $key, $value);
}
if (!$value) {
delete_post_meta($post->ID, $key);
}
}
}