Menu

Creating custom field with drop down on new post page

February 4, 2014 - wordpress

// action to add meta boxes
add_action( ‘add_meta_boxes’, ‘page_location_metabox’ );
// action on saving post
add_action( ‘save_post’, ‘page_location_save’ );

// function that creates the new metabox that will show on post
function page_location_metabox() {
add_meta_box(
‘page_location’, // unique id
__( ‘Add To Home Page’, ‘mytheme_textdomain’ ), // metabox title
‘page_location_display’, // callback to show the dropdown
‘page’ // post type
);
}

// voodoo dropdown display
function page_location_display( $post ) {

// Use nonce for verification
wp_nonce_field( basename( __FILE__ ), ‘page_location_nonce’ );

// get current value
$dropdown_value = get_post_meta( $post->ID, ‘page_location’, true );
?>
<select name=”page_location” id=”page_location”>
<option value=”Yes” <?php if($dropdown_value == ‘Yes’) echo ‘selected=”selected”‘; ?>>Yes</option>
<option value=”No” <?php if($dropdown_value == ‘No’ || $dropdown_value == ”) echo ‘selected=”selected”‘; ?>>No</option>
</select>
<?php
}

// dropdown saving
function page_location_save( $post_id ) {

// if doing autosave don’t do nothing
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE )
return;

// verify nonce
if ( !wp_verify_nonce( $_POST[‘page_location_nonce’], basename( __FILE__ ) ) )
return;
// Check permissions
if ( ‘page’ == $_POST[‘post_type’] )
{
if ( !current_user_can( ‘edit_page’, $post_id ) )
return;
}
else
{
if ( !current_user_can( ‘edit_post’, $post_id ) )
return;
}

// save the new value of the dropdown
$new_value = $_POST[‘page_location’];
update_post_meta( $post_id, ‘page_location’, $new_value );
}

Leave a Reply