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

theme.json导致WordPress伪页面返回404错误的解决方法求助

解决方案:Theme.json 导致伪页面返回404的问题

问题根源

当主题包含theme.json时,WordPress的区块系统会对页面查询进行额外合法性校验,你的伪页面因缺少标准属性、使用非规范状态值,被判定为无效内容触发404;移除theme.json后校验失效,伪页面恢复但丢失区块样式。

具体修复步骤

1. 修正Post状态为标准值

将伪页面的post_status从非标准的static改为WordPress认可的publish:

$post->post_status = 'publish';

2. 补全必要的Post属性

区块系统依赖更多元数据,补充缺失属性并修复语法错误(原代码中$post->post_date缺少分号):

$post->post_date      = $my_date; // 补上缺失的分号
$post->post_date_gmt  = $my_date;
$post->post_modified = $my_date;
$post->post_modified_gmt = $my_date;
$post->post_content_filtered = '';

3. 规范全局变量引用与钩子作用范围

直接使用$wp_query存在作用域问题,需声明全局变量;同时添加URL判断,避免干扰正常页面查询:

add_filter( 'the_posts', 'generate_fake_page', 10);
function generate_fake_page($posts) {
    global $wp_query; // 声明全局WP查询变量
    
    // 仅处理目标伪页面的404请求
    if (!$wp_query->is_404 || strpos($_SERVER['REQUEST_URI'], '/other/') === false) {
        return $posts;
    }

    // 伪页面生成逻辑...
}

4. 强制加载区块样式(可选)

若修复后仍丢失样式,可在函数末尾手动加载主题区块样式:

// 加载WordPress核心区块样式
wp_enqueue_style('wp-block-library');
// 加载主题自定义区块样式(替换为你的主题样式handle)
wp_enqueue_style('your-theme-block-styles');

修复后的完整代码

add_filter( 'the_posts', 'generate_fake_page', 10);
function generate_fake_page($posts) {
    global $wp_query;
    
    // 仅处理目标伪页面的404请求
    if (!$wp_query->is_404 || strpos($_SERVER['REQUEST_URI'], '/other/') === false) {
        return $posts;
    }

    $post = new stdClass;
    $post->post_author    = 1;
    $post->post_name      = $url_slug;
    $post->guid           = home_url() . '/other/';
    $post->post_title     = 'My fake page';
    $post->post_content   = $content;
    $post->ID             = $my_uniq_id;
    $post->post_type      = 'page';
    $post->post_status    = 'publish'; // 修正为标准状态
    $post->post_excerpt   = '';
    $post->comment_status = 'closed';
    $post->ping_status    = 'open';
    $post->comment_count  = 0;
    $post->post_date      = $my_date; // 补充分号
    $post->post_date_gmt  = $my_date;
    $post->post_modified = $my_date; // 新增属性
    $post->post_modified_gmt = $my_date; // 新增属性
    $post->post_content_filtered = ''; // 新增属性

    $posts = [];
    $posts[] = $post;

    // 更新WP查询状态
    $wp_query->is_page             = true;
    $wp_query->is_singular         = true;
    $wp_query->is_home             = false;
    $wp_query->is_archive          = false;
    $wp_query->is_category         = false;
    $wp_query->is_attachment       = false;
    unset( $wp_query->query[ 'error' ] );
    $wp_query->query_vars[ 'error' ] = '';
    $wp_query->is_404 = false;

    // 手动加载区块样式(可选)
    wp_enqueue_style('wp-block-library');
    // wp_enqueue_style('your-theme-block-styles'); // 替换为实际主题样式handle

    return $posts;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:25:28