📝 WordPress: Fix a Custom Field Resetting After Every Autosave
WordPress’s autosave heartbeat fires every 60 seconds and saves a post revision in the background using its own AJAX request, which only posts the fields the editor actually serialized for that revision — not necessarily every custom field on the screen. A meta-box save handler hooked to save_post that unconditionally reads $_POST[‘my_field’] and writes it straight to post meta will see an empty or missing value during that autosave request and happily overwrite the real, previously saved value with nothing.
🔎 The Problem
add_action('save_post', function ($post_id) {
// Runs on every save_post call, including autosave requests,
// where $_POST['event_location'] simply isn't present.
update_post_meta($post_id, 'event_location', $_POST['event_location'] ?? '');
// Result: every autosave quietly blanks out event_location.
});
✅ Fix: Bail Out of Autosave and Ajax Requests Explicitly
- At the top of the save_post handler, return early if
(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)so a background autosave never gets the chance to touch real post meta. - Verify a nonce specific to your meta box before writing anything, and only write a field’s meta if that field’s key is actually present in $_POST, rather than defaulting a missing key to an empty string.
- If the field must stay in sync even during autosave, store it in the revision’s own meta (which WordPress supports per-revision) instead of overwriting the parent post’s meta from an autosave request.
🚨 Why This Is Dangerous
- A field that resets every 60 seconds will eventually catch an editor mid-typing between saves, so the data loss looks random and intermittent instead of pointing straight at the autosave cycle that’s actually causing it.
An autosave is supposed to protect your work, not quietly stand in for it — a meta-box handler that can’t tell the two apart will keep erasing exactly the field it was meant to preserve.

