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

修改Headless Next.js WordPress的Site Address导致草稿无法保存

问题:Headless Next.js WordPress中“保存草稿”请求指向错误地址导致报错

问题描述

基于Vercel示例构建Headless Next.js WordPress应用,本地环境Next.js部署在http://localhost:3000,WordPress部署在http://wordpress.test。已修改WordPress的preview_post_link使其指向Next.js的预览API端点,并将WordPress的**站点地址(URL)**设置为本地Next.js环境地址。修改后“访问站点”“查看文章/页面”按钮可正常跳转至Next.js应用,但“保存草稿”按钮点击时请求会指向http://localhost:3000/wp-json/wp/v2/posts/38?_locale=user(Next.js地址),而非WordPress地址,导致报错。

环境配置

  • WordPress版本:6.1.1
  • 自定义主题
  • functions.php代码:
<?php

add_filter( 'preview_post_link', 'the_preview_fix' );

function the_preview_fix($post) {
    $post = get_post();

    return home_url() . "/api/preview?secret=secret&id={$post->ID}";
}
  • 插件:
    • WPgraphQl 1.14.0
    • WPGraphQL JWT Authentication 0.4.0
  • WordPress设置:
    • WordPress地址(URL):http://wordpress.test
    • 站点地址(URL):http://localhost:3000

原因分析

这不是WordPress的Bug,是你的无头URL设置有误。

WordPress后台的AJAX/REST API请求(包括保存草稿操作)会默认使用**站点地址(URL)**作为请求的基础URL。你将站点地址设为Next.js的地址后,后台内部的API请求会被发往Next.js服务器,但Next.js并没有WordPress的REST API接口,因此导致报错。

你修改的preview_post_link仅影响文章预览的跳转链接,不会改变后台内部API请求的地址逻辑。

解决方案

核心思路是:让WordPress后台内部请求继续使用自身地址,仅将前台对外的链接指向Next.js。

  1. 调整WordPress基本设置:
    将**站点地址(URL)改回WordPress自身地址http://wordpress.test,保留WordPress地址(URL)**不变。

  2. 修改functions.php代码,区分前后台链接:
    通过钩子过滤前台输出的home_url和site_url,让前台链接指向Next.js,后台仍使用WordPress地址:

<?php

// 修改预览链接为Next.js的预览API端点
add_filter( 'preview_post_link', 'custom_preview_link' );
function custom_preview_link($link) {
    $post = get_post();
    return 'http://localhost:3000/api/preview?secret=secret&id=' . $post->ID;
}

// 前台页面输出的home_url指向Next.js
add_filter('home_url', 'custom_frontend_home_url', 10, 3);
function custom_frontend_home_url($url, $path, $orig_scheme) {
    if (!is_admin()) {
        return 'http://localhost:3000' . $path;
    }
    return $url;
}

// 前台页面输出的site_url指向Next.js
add_filter('site_url', 'custom_frontend_site_url', 10, 4);
function custom_frontend_site_url($url, $path, $orig_scheme, $blog_id) {
    if (!is_admin()) {
        return 'http://localhost:3000' . $path;
    }
    return $url;
}
  1. 验证效果:
    • 后台“保存草稿”请求会自动发往http://wordpress.test/wp-json/wp/v2/posts/38?_locale=user,恢复正常。
    • 前台“访问站点”“查看文章/页面”按钮仍会跳转至Next应用,预览链接也保持正确指向Next.js的预览API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:37:03