我将从delete post链接创建一个AJAX调用。
首先,注册AJAX函数:
add_action( \'wp_ajax_wpse_delete_post\', \'wpse_delete_post\' );
我不会向nopriv用户添加AJAX功能,但如果您希望站点的每个访问者(忽略功能)都能够删除帖子,那么您还必须添加以下内容:
add_action( \'wp_ajax_nopriv_wpse_delete_post\', \'wpse_delete_post\' );
接下来要做的是定义回调函数:
function wpse_delete_post() {
// be sure to add all the security you need, so that no post gets deleted by accident or malicious intent
$postid = intval( $_POST[\'post_id\'] );
// also define what you want your AJAX message to return
if ( wp_delete_post( $postid ) === false ) {
echo "fail";
} else {
echo "success";
}
die(); // needed to function properly
}
最后一步是从链接调用AJAX。让我们假设您的链接上有可用的ID,只是为了让事情更简单:
<a href="#" id="POSTID" class="ajax_delete_post">delete post</a>
将以下Javascript添加到函数中:
jQuery(document).ready(function($){
$(".ajax_delete_post").click( function(){
var data = {
action: \'wpse_delete_post\',
post_id: $(this).val("id")
};
$.post(ajaxurl, data, function(response) {
console.log(response);
});
});
});
一定要有
ajaxurl
定义好了,你应该准备好了。