Trigger “unsaved changes” dialog for custom post meta changes
-
16-10-2019 - |
문제
I'm using a custom post type with custom meta fields, but autosave and the "unsaved changes" dialog don't seem to be triggered for these custom meta fields. Autosave isn't as important to me as the unsaved changes dialog - is there a way to trigger it?
function add_meta_boxes() {
add_meta_box('places_location', __('Location'), array(&$this, 'location_box'), 'place', 'normal', 'high');
}
function location_box($post) {
wp_nonce_field(plugin_basename(__FILE__), 'places_location_nonce');
$lat = get_post_meta($post->ID, 'places_lat', true);
$lng = get_post_meta($post->ID, 'places_lng', true);
?>
<p>
<label>
Latitude:
<input name="places_lat" value="<?php echo esc_attr($lat); ?>" />
</label>
<label>
Longitude:
<input name="places_lng" value="<?php echo esc_attr($lng); ?>" />
</label>
</p>
<?php
}
function save_place($id) {
// skip unverified location nonces
if(!wp_verify_nonce($_POST['places_location_nonce'], plugin_basename(__FILE__))) return;
// skip autosave calls
// commenting this out still doesn't trigger saving these fields on autosave
//if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
// update our custom post meta
update_post_meta($id, 'places_lat', (float)$_POST['places_lat']);
update_post_meta($id, 'places_lng', (float)$_POST['places_lng']);
}
해결책
The code indeed only looks at the TinyMCE editor or the title and content field if the editor is hidden:
window.onbeforeunload = function(){
var mce = typeof(tinyMCE) != 'undefined' ? tinyMCE.activeEditor : false, title, content;
if ( mce && !mce.isHidden() ) {
if ( mce.isDirty() )
return autosaveL10n.saveAlert;
} else {
title = $('#post #title').val(), content = $('#post #content').val();
if ( ( title || content ) && title + content != autosaveLast )
return autosaveL10n.saveAlert;
}
};
You could replace that onbeforeunload
handler with your own (be sure to include the existing functionality of course). Or play with the isDirty()
state of the TinyMCE editor and that autosaveLast
value?
다른 팁
I solved this problem using this excellent jQuery plugin that checks the dirty state of a form. It contains methods to checks added/removed/modified fields via javascript. It totally kicks ass!
I did not handled the "AUTOSAVE" (yet). I hope someone finds this useful.