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

如何在WordPress自定义文章类型永久链接中追加日期与企业名称元值?

嘿,我来帮你搞定这个自定义文章类型永久链接的问题!要实现你想要的 www.abc.com/2018/04/best-car-this-year-Honda 格式,咱们一步步来:

1. 完善自定义文章类型的注册配置

首先,确保你注册自定义文章类型(CPT)的代码里,rewrite 参数配置正确,这样才能让后续的 permalink 规则生效。把你现有的注册函数更新成这样:

function Theme2035_detail_register() {
    $args = array(
        'labels' => array(
            'name' => 'Details', // 换成你实际的CPT名称
            'singular_name' => 'Detail'
        ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'custom-fields'), // 必须包含custom-fields才能用元值
        'rewrite' => array(
            'slug' => '%year%/%monthnum%', // 预留年/月的占位符
            'with_front' => false, // 避免继承站点默认的permalink前缀(比如/blog/)
            'feeds' => true,
            'pages' => true
        )
    );
    register_post_type('detail', $args); // 这里的'detail'是你的CPT slug,别写错!
}
add_action('init', 'Theme2035_detail_register');

2. 用过滤器修改永久链接,追加元值

接下来,我们用 post_type_link 过滤器来替换占位符,并且把企业名称元值追加到标题后面。假设你存储企业名称的元键是 company_name,如果不是的话记得替换成你实际使用的键名:

function Theme2035_custom_permalink($post_link, $post) {
    // 只处理我们的自定义文章类型,其他类型直接返回原链接
    if ('detail' !== $post->post_type || 'publish' !== $post->post_status) {
        return $post_link;
    }

    // 获取文章发布日期的年和月
    $year = get_the_date('Y', $post->ID);
    $month = get_the_date('m', $post->ID);

    // 获取企业名称元值,转成URL友好的格式
    $company_name = get_post_meta($post->ID, 'company_name', true);
    $company_suffix = !empty($company_name) ? '-' . sanitize_title($company_name) : '';

    // 替换年/月占位符
    $post_link = str_replace(
        array('%year%', '%monthnum%'),
        array($year, $month),
        $post_link
    );

    // 把企业名称追加到标题后面
    $clean_title = sanitize_title($post->post_title);
    $post_link = str_replace($clean_title, $clean_title . $company_suffix, $post_link);

    return $post_link;
}
add_filter('post_type_link', 'Theme2035_custom_permalink', 10, 2);

3. 刷新重写规则(关键!)

不管你怎么改代码,最后必须刷新WordPress的重写规则,不然新的permalink不会生效。有两种简单方法:

  • 后台操作:登录WP后台,进入「设置」→「固定链接」,不用改任何选项,直接点击「保存更改」就行,系统会自动刷新规则。
  • 代码自动刷新:如果想在主题激活的时候自动刷新,可以加这段代码(避免每次改代码都要去后台点保存):
function Theme2035_flush_rewrite_rules() {
    Theme2035_detail_register();
    flush_rewrite_rules();
}
add_action('after_switch_theme', 'Theme2035_flush_rewrite_rules');

几个要注意的点

  • 确保你给自定义文章类型的文章添加了正确的企业名称元值,元键要和代码里的 company_name 完全一致。
  • 如果你的CPT slug不是 detail,记得把代码里所有的 'detail' 替换成你实际的slug。
  • 测试的时候,新建一篇CPT文章,填写标题、选择发布日期、添加企业名称,然后查看文章的永久链接,应该就符合你的预期了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:00:45