WordPress自定义插件前端文章编辑无法更新问题求助
修复WordPress前端编辑文章失效问题
核心问题分析
- AJAX请求地址错误:
user-posts.js中直接使用PHP代码<?php echo admin_url('admin-ajax.php'); ?>,前端JS无法解析PHP语法,导致请求发送到错误地址,点击更新后无响应。 - 重复提交action参数:表单中已通过隐藏字段
name="action"设置了请求动作,JS中又重复appendaction参数,可能引发参数冲突。
修复后的代码
1. 修正user-posts.js文件
jQuery(document).ready(function($) { $('.delete-post').on('click', function() { var post_id = $(this).data('postid'); var confirmation = confirm('Are you sure you want to delete this post?'); if (confirmation) { $.ajax({ type: 'GET', url: ajax_object.ajax_url, data: { 'action': 'delete_user_post', 'post_id': post_id, 'nonce': ajax_object.edit_post_nonce }, success: function(response) { $('#post-message').html(response); } }); } }); // 处理编辑表单提交 $('#frontend-edit-post-form').on('submit', function(e) { e.preventDefault(); var formData = new FormData(this); // 移除重复的action参数添加,表单中已包含该隐藏字段 $.ajax({ type: 'POST', url: ajax_object.ajax_url, // 使用本地化的AJAX地址 data: formData, processData: false, contentType: false, success: function(response) { console.log('服务器响应:', response); $('#post-message').html(response === 'success' ? '文章更新成功!' : '文章更新失败,请重试。'); }, error: function(xhr, status, error) { console.error('请求错误:', error); $('#post-message').html('请求出错,请检查控制台信息。'); } }); }); });
2. PHP代码验证(无需修改,确认以下配置正确)
确保本地化脚本已正确注册,enqueue_user_posts_script函数中已正确传递ajax_url:
function enqueue_user_posts_script() { wp_enqueue_script('user-posts-script', plugin_dir_url(__FILE__) . 'user-posts.js', array('jquery'), '1.0', true); wp_localize_script('user-posts-script', 'ajax_object', array( 'ajax_url' => admin_url('admin-ajax.php'), 'edit_post_nonce' => wp_create_nonce('edit_post_nonce') )); } add_action('wp_enqueue_scripts', 'enqueue_user_posts_script');
额外优化建议
- 在表单页面添加
id="post-message"的元素,用于显示更新状态:<div id="post-message"></div> - 可以在
handle_frontend_edit_post_submission函数中返回更友好的提示文本,比如替换echo 'success';为echo '文章更新成功!';,增强用户体验。
内容的提问来源于stack exchange,提问作者M Mustamar Natsir
相关产品推荐
相关产品推荐

