我添加了一些控制台。记录函数进行测试,但这基本上与@Chris\\()答案相同:
用于生成菜单内容的菜单回调函数(PHP):
function ajax_menu_callback() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Test</h2>
<br />
<form>
<input id="meta" type ="text" name="1" value="<?php echo esc_html( get_post_meta( 1, \'your_key\', true) ); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
然后在管理端打印javascript(javascript,不要忘记包含jquery库):
jQuery(document).ready(function() {
$("form").submit(function() {
console.log(\'Submit Function\');
var postMeta = $(\'input[name="1"]\').val();
console.log(postMeta);
var postID = 1;
var button = $(\'input[type="submit"]\');
button.val(\'saving......\');
$.ajax({
data: {action: "update_meta", post_id: postID, post_meta: postMeta, },
type: \'POST\',
url: ajaxurl,
success: function( response ) { console.log(\'Well Done and got this from sever: \' + response); }
}); // end of ajax()
return false;
}); // end of document.ready
}); // end of form.submit
然后PHP函数handle update\\u post\\u meta(PHP):
add_action( \'wp_ajax_update_meta\', \'my_ajax_callback\' );
function my_ajax_callback() {
$post_id = $_POST[\'post_id\'];
$post_meta = $_POST[\'post_meta\'];
update_post_meta( $post_id, \'your_key\', $post_meta );
echo \'Meta Updated\';
die();
} // end of my_ajax_callback()