Before to handle the defaut value, there is a lot of changes that you can do for the hook “save_post” and the first one is to no more use it.
You add the metabox only on post type post
, then you can use the hook save_post_post
to only doing the treatment for this custom post :
https://developer.wordpress.org/reference/hooks/save_post_post-post_type/
After that, you don’t need to test the capability edit_post
because the backend page “edit.php” does the test before to save.
And you don’t need to test DOING_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.
Finally, to set a default value in the metabox, you can do it when $update === FALSE
which is called when you click on the link “create a new post”.
and then try this code :
add_action("save_post_post", function ($post_ID, $post, $update) {
if (!$update) {
// default values here
$mydata = get_theme_mod( 'post_layout', 'cover' );
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
return;
}
if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {
return;
}
// check the nonce
check_admin_referer(
"mytheme_build_custom_box"
, "mytheme_build_custom_box_nonce"
);
// save the values
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );
// Update the meta field in the database.
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
}, 10, 3);