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

WordPress自定义文章类型car预览返回404问题求助

解决方案

1. 修复自定义文章类型注册的冗余代码

你在注册CPT的$args数组中重复定义了rewrite参数,保留正确配置即可(覆盖问题会导致部分重写规则不生效):

$args = array(
    'labels' => $labels,
    'public' => true,
    'can_export' => true,
    'has_archive' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_rest' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'capability_type' => 'post',
    'hierarchical' => false,
    'menu_position' => 5,
    'block-editor' => true,
    'rewrite' => array(
        'slug' => $rewrite,
        'with_front' => false // 可选,避免继承固定链接的前端前缀
    ),
    'supports' => array('title', 'editor', 'author', 'thumbnail', 'custom-fields', 'excerpt', 'revisions'),
    'menu_icon' => $icon,
);

2. 优化固定链接刷新逻辑

不要在init钩子每次页面加载都刷新重写规则(会拖慢性能),改为仅在主题/插件激活时执行:

// 替换原来的flush钩子
register_activation_hook(__FILE__, 'prowpsite_theme_rewrite_flush');
function prowpsite_theme_rewrite_flush() {
    prowpsite_create_custom_post_types(); // 先注册CPT再刷新规则
    flush_rewrite_rules();
}

3. 添加自定义重写规则支持ID预览

添加规则让WordPress识别未发布CPT的ID预览路径:

add_action('init', 'add_cpt_preview_rewrite_rule');
function add_cpt_preview_rewrite_rule() {
    // 匹配 /cars/{ID}/ 格式的路径,指向对应的CPT预览
    add_rewrite_rule(
        '^cars/(\d+)/?',
        'index.php?post_type=news&p=$1&preview=true',
        'top'
    );
}

4. 修正预览链接生成(可选)

如果上述规则仍有问题,直接修改预览链接生成逻辑,强制使用带post_type参数的路径:

add_filter('preview_post_link', 'fix_cpt_preview_link', 10, 2);
function fix_cpt_preview_link($preview_link, $post) {
    if ($post->post_type === 'news') {
        // 生成包含post_type参数的预览链接,确保WordPress能正确识别
        $preview_link = add_query_arg(
            array(
                'post_type' => 'news',
                'preview' => 'true'
            ),
            home_url('/?p=' . $post->ID)
        );
    }
    return $preview_link;
}

最后操作

完成上述修改后,进入WordPress后台的设置 → 固定链接页面,直接点击「保存更改」按钮(无需修改任何设置),刷新重写规则使新配置生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:31:34