Can someone help me to add a submit button to any metaboxes i define on my post/page?
<!--Add a button and a nonce-field to your form-->
<input type="hidden" name="my_ajax_nonce" value="<?php echo wp_create_nonce('my_ajax_action');?>" />
<button id="submit-my-form" type="submit"><?php _e('Save custom meta data')?></button>
And then there is my ajax code:
jQuery(document).ready(function($) {
$('body').on('click', '#submit-my-form', function(e) {
e.preventDefault();
var $me = $(this),
action = 'my_ajax_action';
var data = $.extend(true, $me.data(), {
action: action,
form_data: $('#post').serializeArray()
});
$.post(ajaxurl, data, function(response) {
if(response == '0' || response == '-1'){
//TODO: Add Error handling (Wrong nonce, no permissions, …) here.
} else {
//TODO: Do stuff with your response (manipulate DOM, alert user, …)
}
});
});
});
My function code is as follows:
function my_ajax_action() {
if(!wp_verify_nonce( $_POST['my_ajax_nonce'], 'my_ajax_action' )) {
die(-1);
}
//TODO: Add your button saving stuff here.
var_dump($_POST['form_data']);
exit;
}
function my_ajax_action_init() {
if ($_POST['action'] == 'my_ajax_action') {
do_action('wp_ajax_my_ajax_action');
}
}
if (is_admin()){
add_action('wp_ajax_my_ajax_action', 'my_ajax_action');
}
add_action( 'init', 'my_ajax_action_init');
Can someone help to how I can add this to hook to my ACF metabox?