has_tag()
云策文档标注
概述
has_tag() 函数用于检查当前文章是否具有指定的标签。它基于标签的 term_ids、名称或 slugs 进行匹配,并可指定文章对象。
关键要点
- 检查文章是否具有给定标签,参数可为字符串、整数或数组,默认为空以检查是否有任何标签
- 支持在 WordPress Loop 外使用,需提供 $post 参数
- 内部调用 has_term() 函数,专门用于 post_tag 分类法
代码示例
if(has_tag()) {
the_tags();
} else {
//Article untagged
}注意事项
- 整数参数仅匹配标签的 term_ids
- 从 2.7.0 版本起,可在 Loop 外使用,需传入 $post 参数
原文内容
Checks if the current post has any of given tags.
Description
The given tags are checked against the post’s tags’ term_ids, names and slugs.
Tags given as integers will only be checked against the post’s tags’ term_ids.
If no tags are given, determines if post has any tags.
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
$tagstring|int|arrayoptional-
The tag name/term_id/slug, or an array of them to check for. Default empty.
$postint|WP_Postoptional-
Post to check. Defaults to the current post.
Default:
null
Source
function has_tag( $tag = '', $post = null ) {
return has_term( $tag, 'post_tag', $post );
}
Skip to note 3 content
Andrea Castenetto
If the article has tags, show them. Else do nothing. It works in the loop.
if(has_tag()) { the_tags(); } else { //Article untagged }Skip to note 4 content
Andrea Castenetto
If Post has tag, show them. Else if Post has category, show category. Otherwise do other.
if(has_tag()) { the_tags(); //show tags } elseif(has_category()) { the_category(); //show category } else { //do something different }