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

WordPress自定义文章类型单页输出当前分类slug失败求助

WordPress 自定义文章类型单页分类Slug输出问题修复

你的代码存在几个关键问题,导致无法正常输出分类slug:

  • wp_get_post_terms 第一个参数需传入文章ID,而非文章slug,正确参数应为 get_the_ID() 或 $post->ID
  • 从你的链接product-category判断,自定义文章类型product的分类应该是自定义分类法product_category,而非默认的category
  • wp_get_post_terms 返回的是分类对象数组,不能直接通过$terms->slug访问,需先判断数组是否有效,再取第一个分类的slug
  • 硬编码相对路径../../product-category/易出现路径错误,建议用WordPress内置函数get_term_link()生成可靠的分类链接

修正后的代码如下:

if ( 'product' == get_post_type() ) {
    // 获取当前文章关联的product_category分类
    $terms = wp_get_post_terms( get_the_ID(), 'product_category' );
    // 确保获取到有效分类数据
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
        $term = $terms[0];
?>
<center><a href="<?php echo esc_url( get_term_link( $term ) ); ?>" class="grve-btn grve-btn-small grve-square grve-bg-primary-1 grve-bg-hover-black">Back</a></center>
<?php
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:35:59