Not sure why my custom post meta field isn’t saving

Register your save handler with two accepted arguments:

add_action('save_post', 'save_details', 10, 2 );

You get two important parameters now:

function save_details( $post_id, $post ) {}

The first is the post ID, the second the complete post object. Do not rely on a global post object. In some situations it is not available, bulk edit for example.

Then use a nonce filed in your metabox output to make sure you handle only values sent per your box:

echo wp_nonce_field( 'job_location', '_nonce_job_location' );

In your save handler validate the nonce with:

if ( ! wp_verify_nonce( $_POST[ '_nonce_job_location' ], 'job_location' ) )
    return;

During an auto-save request the extra fields are not sent, so do not do anything when DOING_AUTOSAVE ist defined:

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;

And test if the user is allowed to edit the current post:

if ( ! current_user_can( 'edit_post', $post_id ) )
    return;

After all these checks you can save or delete the data.

Leave a Comment