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

无法为函数添加第二个分类法术语至body类的问题咨询

问题原因与修复方案

你的代码问题出在get_the_terms()函数的参数使用上:这个函数的第二个参数只能传入单个分类法名称,你把arbocategory和portfolio_category同时放在一个函数调用里,函数只会处理第一个分类法,第二个会被直接忽略,所以新增的分类无法生效。

修复后的代码如下:

//add taxonomy to body class
add_filter( 'body_class', 'themeprefix_add_taxonomy_class' );
// Add taxonomy terms name to body class
function themeprefix_add_taxonomy_class( $classes ){
    if( is_singular() ) {
        global $post;
        // 处理arbocategory分类法
        $arbocategory_terms = get_the_terms($post->ID, 'arbocategory');
        if ( $arbocategory_terms ) {
            foreach ( $arbocategory_terms as $term ) {
                $classes[] = 'tax_' . $term->slug;
            }
        }
        // 处理portfolio_category分类法
        $portfolio_category_terms = get_the_terms($post->ID, 'portfolio_category');
        if ( $portfolio_category_terms ) {
            foreach ( $portfolio_category_terms as $term ) {
                $classes[] = 'tax_' . $term->slug;
            }
        }
    }
    return $classes;
}

逻辑说明:

  • 分别对两个分类法调用get_the_terms()获取对应术语
  • 各自判断术语是否存在,存在则循环添加到body类数组中
  • 后续如果需要添加更多分类法,重复上述步骤即可,每个分类法的术语都会以tax_术语别名的格式添加到body标签上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:20:42