Home  >  Q&A  >  body text

"WordPress's has_term() function does not work as expected"

I have a custom article taxonomy defined as follows:

// 为文章注册自定义分类法
function custom_taxonomy_page_type_for_posts() {
    $labels = array(
        'name'              => _x( '页面类型', '分类法通用名称' ),
        'singular_name'     => _x( '页面类型', '分类法单数名称' ),
        ...

    $args = array(
        'hierarchical'      => false,
        ...
        'rewrite'           => array( 'slug' => 'page-type' ),
        'show_in_rest'      => true,
    );

    register_taxonomy( 'page_type', 'post', $args );
}

In the following code, I want to add a body class based on whether the current article is assigned as a "newsletter" page type.

/* 这将在body标签上添加“vn-briefing”或“vn-not-briefing”类。 */
function add_page_type_css_class($classes) {
    if (is_singular('post')) {
        // 检查文章是否被分配了ID为187的“页面类型”分类法
        if (has_term('Briefing', 'Page Types')) {
            $classes[] = 'is-briefing';
        } else {
            $classes[] = 'is-not-briefing';
        }
    }
    return $classes;
}
add_filter('body_class', 'add_page_type_css_class');

Even if the article is assigned the "Page Type" with ID=187 as "Newsletter", it always returns false.

I expected the function to return true if the post was assigned the "Newsletter" page type, but it doesn't.

I also tried:

has_term('Briefing', 'Page Type')
   has_term('Briefing', 'page-type')

How should I do this?

P粉248602298P粉248602298382 days ago469

reply all(1)I'll reply

  • P粉022723606

    P粉0227236062023-09-07 10:08:18

    The correct syntax should be has_term('briefing', 'page_type'). Here is the updated code:

    function add_page_type_css_class($classes) {
      if (is_singular('post')) {
        // 检查帖子是否有“页面类型”分类法,其别名为 'briefing'
        if (has_term('briefing', 'page_type')) {
            $classes[] = 'is-briefing';
        } else {
            $classes[] = 'is-not-briefing';
        }
     }
     return $classes;
    }
    add_filter('body_class', 'add_page_type_css_class');

    reply
    0
  • Cancelreply