I have a custom article taxonomy defined as follows:
// 為文章注冊自定義分類法 function custom_taxonomy_page_type_for_posts() { $labels = array( 'name' => _x( '頁面類型', '分類法通用名稱' ), 'singular_name' => _x( '頁面類型', '分類法單數(shù)名稱' ), ... $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?
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');