Wordpress has_term() not working as expected - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Thursday, July 6, 2023

Wordpress has_term() not working as expected

I hava custom taxonomy for posts defined as follows:

// Register custom taxonomy for posts
function custom_taxonomy_page_type_for_posts() {
    $labels = array(
        'name'              => _x( 'Page Types', 'taxonomy general name' ),
        'singular_name'     => _x( 'Page Type', 'taxonomy singular name' ),
        ...

    $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 depending on whether on not the current post is assigned a Page Type of "Briefing".

/* This either adds the class "vn-briefing" or "vn-not-briefing" to the body tag. */
function add_page_type_css_class($classes) {
    if (is_singular('post')) {
        // Check if the post has a "Page Types" taxonomy assigned with 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');

It always returns false even if the post is assigned 'Page Type' of ID=187 Briefing.

I was expecting the function to return true if the post was assigned a Page Type of "Briefing" but it doesn't.

I've also tried:

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

Any thoughts would be appreciated. Thanks.



source https://stackoverflow.com/questions/76622966/wordpress-has-term-not-working-as-expected

No comments:

Post a Comment