I have added a custom field to the regular WP post type and added a meta box to the post editor as below (it is just an example with trivial checkbox):
add_action( 'add_meta_boxes', 'add_meta_box_my_custom_field' );
function add_meta_box_my_custom_field()
{
add_meta_box(
'my_custom_field', // $id
__( 'My Custom Field', 'mycustomfield' ), // $title
'display_my_custom_field_meta_box', // $callback
'post', // $screen
'side', // $context
'low', // $priority
);
}
add_action( 'save_post', 'save_my_custom_field_value' );
function save_my_custom_field_value($post_id)
{
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !current_user_can( 'edit_post' ) ) return;
$new_value = isset( $_POST['my_custom_field'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'my_custom_field', $new_value );
}
function display_my_custom_field_meta_box(){
global $post;
$check=get_post_custom( $post->ID );
$checked_value = isset( $check['my_custom_field'] ) ? esc_attr( $check['my_custom_field'][0] ) : 'no';
?>
<label for="my_custom_field"><?php _e( 'My Custom Field', 'mycustomfield' ); ?>:</label>
<input type="checkbox" name="my_custom_field" id="my_custom_field" <?php if($checked_value=="yes"){echo "checked=checked"; } ?> >
<p><em><?php _e( 'Enable My Custom Field.', 'mycustomfield' ); ?></em></p>
<?php
}
It works fine in standard WP installation with block editor etc. The only thing that does not seem to work is the detection of unsaved changes.
When I open the post to edit it, change current setting of 'My Custom Field' and try to navigate out of the page, I do not get the warning. Unsaved changes are lost.
I have played with changing the priorities, different hooks, but got eventually clueless. Thus, it must be something really trivial that I am missing. Can anybody provide a hint?
yes
if it's set, even if it's unchecked, the scenario I mentioned isn't handled by the code, It looks like you assumed that if$_POST['my_custom_field']
is only set when the box is checked, which may be a bad assumption. You're assuming that if the user unchecks the box, then$_POST['my_custom_field']
is not set, are you sure about that?