You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义插件前端文章编辑无法更新问题求助

修复WordPress前端编辑文章失效问题

核心问题分析

  1. AJAX请求地址错误:user-posts.js中直接使用PHP代码<?php echo admin_url('admin-ajax.php'); ?>,前端JS无法解析PHP语法,导致请求发送到错误地址,点击更新后无响应。
  2. 重复提交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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:25:53