I’m getting this error with my custom post metabox. The custom post and metabox works fine, but if i have debug on and when i try to save any other page or post, i will get an error:
Notice: Undefined index: at_nonce in
/Users/jay/site/wp-content/themes/mytheme/dogs-post-type.php on line
53Notice: Undefined index: at_nonce in
/Users/jay/site/wp-content/themes/mytheme/dogs-post-type.php on line
53Warning: Cannot modify header information – headers already sent by
(output started at
/Users/jay/site/wp-content/themes/mytheme/dogs-post-type.php:53) in
/Users/jay/site/wp-includes/pluggable.php on line 876
My code:
<?php
// Add new custom post for dogs
function example_dogs_custom_init() {
$args = array(
'label' => 'Dogs',
'public' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'menu_position' => 5,
'supports' => array('title', 'editor'),
'rewrite' => array('slug' => 'pets/dogs', 'with_front' => false)
);
register_post_type( 'dogs', $args );
}
add_action( 'init', 'example_dogs_custom_init' );
// METABOX breed
add_action("add_meta_boxes", 'test_add_post_meta_boxes_breed');
function test_add_post_meta_boxes_breed() {
add_meta_box(
'breed-meta', // Unique ID
'Breed', // Title
'breed_cb', // Callback function
'dogs', // Admin page (or post type)
'side', // Context
'default' // Priority
);
}
function breed_cb() {
global $post;
$breed_input = get_post_meta($post->ID, 'breed_field', true);
// unique identifier, name of hidden field
wp_nonce_field(__FILE__, 'at_nonce');
?>
<label for="breed_field">Breed:</label>
<input type="text" name="breed_field" id="breed_field" value="<?php echo $breed_input; ?>" />
<br><span></span><?php
}
add_action('save_post', function() {
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
// security check - nonce
// verify this came from the our screen and with proper authorizarion,
// because save_post can be triggered at other times
if ( $_POST && !wp_verify_nonce($_POST['at_nonce'], __FILE__) ) {
return;
}
if ( isset($_POST['breed_field']) ) {
update_post_meta($post->ID, 'breed_field', $_POST['breed_field']);
}
});
?>
There is something wrong with the nonce field but i cant figure out what. If it helps, the code structure is from Jeffrey Ways The Magic of WordPress Custom Post Types course.
2 Answers
These are your problem lines:
if ( $_POST && !wp_verify_nonce($_POST['at_nonce'], __FILE__) ) {
return;
}
You check to see that $_POST
is set, but you don’t check $_POST['at_nonce']
. If $_POST
is set but that key is not then you will get a Notice
. It is a simple fix:
if ( isset($_POST['at_nonce']) && !wp_verify_nonce($_POST['at_nonce'], __FILE__) ) {
return;
}
When that Notice
prints, content is sent to the browser. Since that content is being sent before the proper headers are sent, when those proper headers are sent you get the “Cannot modify header information” warning.