I am trying to add a new select field to the page properties sidebar, but I am having trouble getting it to save the value.
This is what I have at the moment:
<?php
function addMyMeta() {
add_meta_box( 'my_custom_metabox', 'My Meta', 'setMyMeta', 'page', 'side', 'default' );
}
add_action( 'add_meta_boxes', 'addMyMeta' );
function setMyMeta() {
global $page;
$value = get_post_meta( $page->ID, 'my_custom_metabox', true );
?>
<fieldset>
<select name="my_custom_metabox" id="my_custom_metabox" autocomplete="off">
<option value="">Default</option>
<option value="my-value" <?php if($value == 'my-value') {echo ' selected ';}; ?>>My Value</option>
</select>
</fieldset>
<?php
}
function saveMyMeta( $page_id, $page ) {
if ( !isset( $_POST['my_custom_metabox'] ) ) {
update_post_meta( $page->ID, 'my_custom_metabox', $_POST['my_custom_metabox'] );
}
}
add_action( 'save_post', 'saveMyMeta', 1, 2 );
?>
2
Answers
Change
global $page;
toglobal $post;
and$value = get_post_meta( $post->ID, 'my_custom_metabox', true );
You should use
isset
instead of!isset
insaveMyMeta
function. Why would you want to run theupdate_post_meta
if the value is not even set?I prefer to add meta boxes using OOP because it’s easy and saves you from having to worry about naming collisions in the global namespace.
Things to consider using while adding meta boxes:
post_type
suffix to save_post action hook. in your case it will besave_post_page
.Here is the full OOP code: