"WordPress's has_term() function does not work as expected"
P粉248602298
P粉248602298 2023-09-06 15:59:22
0
1
520

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粉248602298
P粉248602298

reply all(1)
P粉022723606

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');
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template