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

如何为WordPress的custom post type设置多URL规则匹配不同模板?

WordPress 动态模板加载方案(无需创建多篇文章)

1. 注册自定义文章类型(若未完成)

先确保company自定义文章类型注册正确,重点开启重写支持:

function register_company_cpt() {
    $args = array(
        'public' => true,
        'label'  => '企业',
        'rewrite' => array( 'slug' => 'company' ),
        // 按需添加其他参数(如支持字段、菜单图标等)
    );
    register_post_type( 'company', $args );
}
add_action( 'init', 'register_company_cpt' );

注册后前往「设置-固定链接」刷新一次重写规则。

2. 添加自定义重写规则与查询变量

为支持你提到的两种URL结构,添加重写规则解析template_name和company_name,同时将这两个变量加入WordPress查询白名单:

function add_company_rewrite_rules() {
    // 处理路径式URL:example.com/company/template_name/bla_invest
    add_rewrite_rule(
        '^company/([^/]+)/([^/]+)/?$',
        'index.php?post_type=company&template_name=$matches[1]&company_name=$matches[2]',
        'top'
    );
    
    // 处理带查询参数的URL:example.com/company/template_name/?company_name=bla_invest
    add_rewrite_tag( '%template_name%', '([^&]+)' );
    add_rewrite_tag( '%company_name%', '([^&]+)' );
}
add_action( 'init', 'add_company_rewrite_rules' );

完成后再次刷新固定链接使规则生效。

3. 根据template_name动态加载模板

使用template_include钩子,依据当前查询的template_name值加载对应模板文件:

function load_company_template( $template ) {
    // 仅在company自定义文章类型页面生效
    if ( get_post_type() !== 'company' ) {
        return $template;
    }
    
    $template_name = get_query_var( 'template_name' );
    // 定义允许的模板标识,对应你的三个模板
    $allowed_templates = array( 'profile', 'finance', 'projects' );
    
    if ( in_array( $template_name, $allowed_templates ) ) {
        $custom_template = locate_template( "template-company-$template_name.php" );
        if ( $custom_template ) {
            return $custom_template;
        }
    }
    
    // 无匹配模板时返回默认模板
    return $template;
}
add_filter( 'template_include', 'load_company_template' );

这里假设你的三个模板文件名为template-company-profile.php、template-company-finance.php、template-company-projects.php,直接放在主题根目录即可。

4. 在模板中获取企业数据

在对应模板文件内,通过get_query_var('company_name')获取动态企业名称,再加载对应数据:

// 示例:template-company-profile.php 中的代码
$company_name = get_query_var( 'company_name' );
// 根据企业名称查询数据,比如从自定义字段、数据库或API获取
$company_data = get_company_data_by_name( $company_name ); // 此函数需自行实现

注意事项

  • 每次修改重写规则后,必须刷新固定链接缓存。
  • 若主题使用自定义模板层次,确保locate_template能正确定位到你的模板文件。
  • 可添加额外校验逻辑,比如判断company_name是否有效,避免加载无效数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:25:03