Skip to content

Instantly share code, notes, and snippets.

@krasenslavov
Last active November 7, 2021 19:12
Show Gist options
  • Save krasenslavov/7b62ea69eac85007523bf62ec0bb329e to your computer and use it in GitHub Desktop.
Save krasenslavov/7b62ea69eac85007523bf62ec0bb329e to your computer and use it in GitHub Desktop.
ACF Autosave & Live Preview (using sessionStorage)
(function($) {
$(document).on('change', '.acf-postbox [id^="acf-field"]', function(e) {
e.preventDefault();
var permalink = $('#sample-permalink a').attr('href');
if (!sessionStorage.getItem(permalink)) {
sessionStorage.setItem('permalink', permalink);
}
$('input[type="submit"]#publish').val('Updating...').addClass('button-disabled');
$.ajax({
method: 'post',
url: hm_autosave.ajaxurl,
data: {
action: 'hm_autosave',
post_id: $('#post_ID').val(),
acf_name: $(this).closest('.acf-field').data('name'),
acf_value: $(this).val()
}
}).done(function(message) {
$('input[type="submit"]#publish').val('Update').removeClass('button-disabled');
var win = window.open(
sessionStorage.getItem('permalink'),
'Preview Window',
'height=1680,width=1200');
win.location.reload();
});
});
})(jQuery);
<?php
function hm_register_admin_scripts()
{
$theme_version = wp_get_theme()->get('Version');
wp_enqueue_script(
'admin-js',
get_template_directory_uri() . '/admin.js',
array(),
$theme_version,
true
);
wp_localize_script(
'admin-js',
'hm_autosave',
array(
'ajaxurl' => admin_url('admin-ajax.php')
)
);
}
add_action('admin_enqueue_scripts', 'hm_register_admin_scripts');
function hm_autosave()
{
if ($_REQUEST['post_id'] && $_REQUEST['acf_name']) {
update_post_meta(
esc_attr($_REQUEST['post_id']),
$_REQUEST['acf_name'],
$_REQUEST['acf_value']
);
}
exit;
}
add_action('wp_ajax_hm_autosave', 'hm_autosave');
add_action('wp_ajax_nopriv_hm_autosave', 'hm_autosave');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment