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

修改URL/添加CPT时Polylang Pro致次要语言页404的预防方法

解决Polylang Pro修改固定链接/新增CPT后次要语言404的预防方案

自动触发Polylang重写规则刷新

通过WordPress钩子,在固定链接修改或自定义文章类型(CPT)注册完成后,自动调用Polylang的规则刷新函数,替代手动保存设置的操作:

  • 添加以下代码到主题的functions.php文件或自定义功能插件中:
    // 固定链接结构修改时刷新Polylang重写规则
    add_action('permalink_structure_changed', function() {
        if (function_exists('pll_flush_rewrite_rules')) {
            pll_flush_rewrite_rules();
        }
    });
    
    // 注册新CPT时刷新Polylang重写规则
    add_action('registered_post_type', function($post_type) {
        // 可根据需求添加CPT名称判断,仅针对特定类型触发
        // if ($post_type === 'your_custom_post_type') { ... }
        if (function_exists('pll_flush_rewrite_rules')) {
            pll_flush_rewrite_rules();
        }
    }, 10, 1);
    

确保CPT注册与Polylang兼容

注册自定义文章类型时,需同步处理重写规则的兼容性:

  • 在CPT注册函数的末尾,同时刷新WordPress原生重写规则和Polylang规则:
    function register_my_cpt() {
        $args = array(
            'public' => true,
            'label'  => 'My CPT',
            'rewrite' => array('slug' => 'my-cpt')
            // 其他CPT参数...
        );
        register_post_type('my_cpt', $args);
    
        // 刷新规则
        flush_rewrite_rules();
        if (function_exists('pll_flush_rewrite_rules')) {
            pll_flush_rewrite_rules();
        }
    }
    add_action('init', 'register_my_cpt');
    

避免缓存插件干扰

部分缓存插件会缓存重写规则,导致Polylang的新规则无法生效:

  • 修改固定链接或新增CPT前,临时禁用缓存插件,操作完成后再重新启用;
  • 配置缓存插件,排除Polylang语言相关的URL路径,避免旧规则被持久缓存。

定期验证规则状态

在WordPress核心、主题或插件更新后,手动确认Polylang的URL重写规则正常:

  • 可通过调用pll_flush_rewrite_rules()函数(比如在临时调试页面中执行),批量刷新所有语言的重写规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:26:01