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

WordPress中AJAX执行insert_post成功后如何返回并显示新文章ID与URL

实现方案

完全可以在success回调中拿到所需数据,只需调整后端返回逻辑与前端接收逻辑,修改步骤如下:


第一步:修改functions.php中的接口处理逻辑

原来的接口仅返回成功/失败字符串,你需要在插入成功后组装文章ID、URL、标题数据,以JSON格式返回:

function save_enquiry_form_action() {
     
    $post_title = $_POST['post_details']['post_title'];
    $post_description = $_POST['post_details']['post_description'];
    $args = [
        'post_title'=> $post_title,
        'post_content'=> $post_description,
        'post_status'=> 'publish',
        'post_type'=> 'post',
        'show_in_rest' => true,
        'post_date'=> get_the_date()
    ];
 
    $post_id = wp_insert_post($args);
 
    if($post_id) {
        // 组装返回数据
        $return_data = [
            'code' => 1,
            'msg' => 'success',
            'post_id' => $post_id,
            'post_title' => $post_title,
            'post_url' => get_permalink($post_id) // 获取文章URL
        ];
        wp_send_json($return_data); // WordPress内置方法返回JSON
    } else {
        $return_data = [
            'code' => 0,
            'msg' => 'failed'
        ];
        wp_send_json($return_data);
    }
    wp_die();
}

第二步:修改前端代码

首先调整模态框的展示区域,增加ID方便JS操作,移除无用的PHP代码(页面渲染完成后PHP代码已执行完毕,异步请求无法再触发PHP执行):

<div id="tvesModal" class="modalContainer">
 <div class="modal-content">
 <span class="close">×</span> <h2>模态框</h2>
 <!-- 给展示区域加ID -->
 <p id="modal-post-info"></p> 
 </div>
</div>

然后修改AJAX请求配置与success回调逻辑,指定接收JSON格式数据,拿到返回值后插入到模态框中:

$("#enquiry_email_form").on("submit", function (event) {
    event.preventDefault();

    var form= $(this);
    var ajaxurl = form.data("url");
    var detail_info = {
        post_title: form.find("#post_title").val(),
        post_description: form.find("#post_description").val()
    }

    if(detail_info.post_title === "" || detail_info.post_description === "") {
        alert("字段不能为空");
        return;
    }

    $.ajax({
        url: ajaxurl,
        type: 'POST',
        dataType: 'json', // 新增:指定返回数据为JSON格式
        data: {
            post_details : detail_info,
            action: 'save_post_details_form'
        },
        error: function(error) {
            alert("插入失败" + error);
        },
        success: function(response) {
            if(response.code === 1) {
                // 把拿到的文章数据拼接后插入模态框
                $('#modal-post-info').html(`文章标题:${response.post_title}<br>文章ID:${response.post_id}<br>文章URL:<a href="${response.post_url}" target="_blank">${response.post_url}</a>`)
                modal.style.display = "block";  // 打开模态框
                body.style.position = "static";
                body.style.height = "100%";
                body.style.overflow = "hidden";
            } else {
                alert("文章插入失败,请重试");
            }
        }
    });
})

内容的提问来源于stack exchange,提问作者juan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:15:02