使用AJAX删除WordPress文章

我们在用wordpress做网站时,写的文章或是测试的文章很多,但后期我们确需要删除某些文章时。用传统的方法一篇一篇的删除耗时确实太长了。用数据库删除方法对于一般新手又太难。那有没有一种方便快捷的删除文章的方法呢。肯定就是有,利用ajax无刷新删除文章又快又方便。就如下图一样

Wordpress Admin Ajax Remove Posts

教程分为两个部分。一个是js。如下代码

jQuery(function($){
$('body.post-type-post .row-actions .trash a').click(function( event ){
event.preventDefault();
var url = new URL( $(this).attr('href') ),
    nonce = url.searchParams.get('_wpnonce'), // MUST for security checks
    row = $(this).closest('tr'),
    postID = url.searchParams.get('post'),
    postTitle = row.find('.row-title').text();
row.css('background-color','#ffafaf').fadeOut(300, function(){
row.removeAttr('style').html('<td colspan="5">Post <strong>' + postTitle + '</strong> moved to the Trash.</td>').show();
});
$.ajax({
method:'POST',
url: ajaxurl,
data: {
'action' : 'moveposttotrash',
'post_id' : postID,
'_wpnonce' : nonce
}
});
});
});

把上面的代码保存为一个js文件。如movepost.js。然后在后台引用它。具体的引用办法请参考如何在WordPress主题和插件中正确加载CSS和JS

第二个是php文件。把下面的代码放在您主题的function.php文件里即可。

add_action('wp_ajax_moveposttotrash', function(){
check_ajax_referer( 'trash-post_' . $_POST['post_id'] );
wp_trash_post( $_POST['post_id'] );
die();
});

就这么简单。

本文已在Ie主题99839发布

文章来源:https://ietheme.com/remove-posts-with-ajax.html


撰写评论

您的电子邮箱地址不会被公开。 必填项已用*标注

加入我们

注册完成!

密码重置

请输入您的邮箱地址。 您将收到一个链接来创建新密码。

检查你的邮件中的确认链接。