WordPress后台使用ajax高效快速删除文章
要在WordPress后台使用ajax来快速删除文章,你可以按照以下步骤操作:

- 注册并入队脚本
首先,你需要确保你的JavaScript文件(我们这里叫做customadmin.js)已经被入队:
function enqueue_custom_admin_scripts() {
    wp_enqueue_script('customadminjs', get_template_directory_uri() . '/js/customadmin.js', array('jquery'), '1.0.0', true);
    // 将Ajax URL和nonce传递给JavaScript文件
    wp_localize_script('customadminjs', 'ajax_params', array(
        'ajax_url' => admin_url('adminajax.php'),
        'nonce' => wp_create_nonce('delete_post_nonce'),
    ));
}
add_action('admin_enqueue_scripts', 'enqueue_custom_admin_scripts');- 创建JavaScript文件
在你的customadmin.js文件中,添加以下代码来处理点击删除按钮时的动作:
jQuery(document).ready(function($) {
    $(document).on('click', '.customdeletepost', function(e) {
        e.preventDefault();
        var post_id = $(this).data('postid');
        $.ajax({
            type: 'POST',
            url: ajax_params.ajax_url,
            data: {
                action: 'custom_delete_post',
                post_id: post_id,
                nonce: ajax_params.nonce
            },
            success: function(response) {
                if(response == 'success') {
                    alert('文章已删除!');
                    // 你可以在这里添加其他的行为,比如隐藏被删除文章的行
                } else {
                    alert('删除失败!');
                }
            }
        });
    });
});- 处理Ajax请求
在你的functions.php文件或者一个合适的插件文件中,添加以下代码来处理Ajax请求:
function custom_delete_post() {
    // 检查nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'delete_post_nonce')) {
        echo '非法请求';
        die();
    }
    if(isset($_POST['post_id'])) {
        $post_id = intval($_POST['post_id']);
        if(wp_trash_post($post_id)) {
            echo 'success';
        } else {
            echo 'fail';
        }
        die();
    }
}
add_action('wp_ajax_custom_delete_post', 'custom_delete_post');- 添加删除按钮
在你想要的地方(可能是文章列表的一个位置),添加删除按钮:
<a href="#" class="customdeletepost" datapostid="<?php echo get_the_ID(); ?>">删除</a>以上代码是一个简化版的示例,你可能需要根据自己的实际需求进一步完善它。但基本思路是这样的:在后台创建一个ajax请求来删除文章,并在成功时给出反馈。
 
                        仍然有问题? 我们要如何帮助您? 
                    
                 
             
             
             
             
        

 
                        