WordPress函数:has_term 检查文章是否包含分类、标签等

追格官方小助手/ 2022年08月24日/ WordPress/ 浏览 1382

之前介绍过 has_taghas_category 函数,这两个函数其实都是 has_term 函数的封装。

has_term 支持任意文章分类、标签的检查。


函数原型:


has_term( string|int|array $term = '', string $taxonomy = '', int|WP_Post $post = null )


将给定的术语与post的term_id、名称和slug进行比较。以整数形式给出的术语将仅根据post的术语“term_id”进行检查。


如果未给出任何分类,则确定post是否有任何分类。


函数源码:


function has_term( $term = '', $taxonomy = '', $post = null ) {
    $post = get_post( $post );
 
    if ( ! $post ) {
        return false;
    }
 
    $r = is_object_in_term( $post->ID, $taxonomy, $term );
    if ( is_wp_error( $r ) ) {
        return false;
    }
 
    return $r;
}


使用举例:


$hook_css_class = '';
if (has_term( 'action', 'hook-type' )) {
  $hook_css_class = "is-action-hook";
} else {
  $hook_css_class = "is-filter-hook";
};


发表评论

暂无评论,抢个沙发...

客服 工单