WordPress:AJAX请求成功但custom posts删除失败问题求助
问题分析与解决方案
你遇到的问题是AJAX请求虽成功但无法删除文章,核心原因集中在ID传递、权限验证和响应逻辑上,以下是具体修复方案:
修正后的短代码函数
function wpso_delete_my_posts($atts) { // 提取短代码参数,默认空ID $atts = shortcode_atts(array( 'id' => '' ), $atts); $post_id = absint($atts['id']); if (!$post_id) return ''; // 无效ID直接返回空 $current_user = get_current_user_id(); $author_id = get_post_field('post_author', $post_id); ob_start(); // 验证权限:作者本人或管理员 if ($author_id == $current_user || current_user_can('administrator')) { echo '<a class="delete-post" rel="nofollow" href="#" data-post-id="' . $post_id . '">Delete Listing</a>'; } return ob_get_clean(); } add_shortcode('delete_me', 'wpso_delete_my_posts');
使用短代码时需传入文章ID:[delete_me id="123"]
修正后的AJAX函数
// 登录用户的AJAX钩子 add_action('wp_ajax_send_post_to_draft', 'send_post_to_draft_callback'); // 非登录用户(若无需开放给游客可删除此行) add_action('wp_ajax_nopriv_send_post_to_draft', 'send_post_to_draft_callback'); function send_post_to_draft_callback() { // 检查ID有效性 if (!isset($_POST['post_id']) || !is_numeric($_POST['post_id'])) { wp_send_json_error('无效的文章ID'); } $post_id = absint($_POST['post_id']); $current_user = get_current_user_id(); $author_id = get_post_field('post_author', $post_id); // 二次验证权限,防止前端篡改 if ($author_id != $current_user && !current_user_can('administrator')) { wp_send_json_error('无权限删除该文章'); } // 执行删除,true为永久删除,false则移至回收站 $deleted = wp_delete_post($post_id, true); if ($deleted) { wp_send_json_success('文章已删除'); } else { wp_send_json_error('删除失败,文章可能不存在'); } }
修正后的AJAX请求代码
// 用class绑定事件,支持多文章场景 $('.delete-post').click(function(e) { e.preventDefault(); var postId = $(this).data('post-id'); $.ajax({ url: bbjs.ajaxurl, type: 'POST', data: { action: 'send_post_to_draft', post_id: postId // 传递文章ID给后端 }, success: function(response) { if (response.success) { alert(response.data); // 删除成功后可移除页面上的文章元素 $(this).closest('.post-item').remove(); } else { alert('Error: ' + response.data); } }.bind(this), // 绑定当前按钮的上下文 error: function() { alert('Error: AJAX请求失败'); } }); });
关键修复点说明
- ID传递逻辑:前端通过
data-post-id存储文章ID,AJAX请求时传给后端,避免依赖全局$post对象导致的ID获取失败 - 权限二次验证:后端重新验证用户权限,防止前端被篡改绕过权限限制
- 标准化响应:使用
wp_send_json_success和wp_send_json_error返回标准JSON响应,让前端能准确判断操作结果 - 多按钮兼容:用class替代ID绑定点击事件,解决多文章场景下按钮ID重复导致的事件失效问题
内容的提问来源于stack exchange,提问作者Victor Cojocaru
相关产品推荐
相关产品推荐

