不久前发布了一篇教程,介绍了如何使用ajax通知发布/更新帖子,下面是其中的代码:
function my_post_type_xhr(){
global $post;
if(\'my_post_type\' === $post->post_type){
$post_url = admin_url(\'post.php\'); #In case we\'re on post-new.php
echo "
<script>
jQuery(document).ready(function($){
//Click handler - you might have to bind this click event another way
$(\'input#publish, input#save-post\').click(function(){
//Post to post.php
var postURL = \'$post_url\';
//Collate all post form data
var data = $(\'form#post\').serializeArray();
//Set a trigger for our save_post action
data.push({foo_doing_ajax: true});
//The XHR Goodness
$.post(postURL, data, function(response){
var obj = $.parseJSON(response);
if(obj.success)
alert(\'Successfully saved post!\');
else
alert(\'Something went wrong. \' + response);
});
return false;
});
});
</script>";
}
}
add_action(\'admin_head-post.php\', \'my_post_type_xhr\');
add_action(\'admin_head-post-new.php\', \'my_post_type_xhr\');
它还有第二部分: add_action(\'save_post\', \'save_my_post_type\');
function save_my_post_type($post_id){
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) return;
#If this is your post type
if(\'my_post_type\' === $_POST[\'post_type\']){
//Save any post meta here
#We conditionally exit so we don\'t return the full wp-admin load if foo_doing_ajax is true
if(isset($_POST[\'foo_doing_ajax\']) && $_POST[\'foo_doing_ajax\'] === true){
header(\'Content-type: application/json\');
#Send a response
echo json_encode(array(\'success\' => true));
exit;
#You should keep this conditional to degrade gracefully for no JS
}
}
}
虽然此解决方案可行,但它有几个缺陷:在该代码段中,没有弹出消息表明该帖子类型已保存。在该代码段中,您可以在离开帖子类型时发出警告,询问您是否要离开,即使帖子已更新
谢谢