has_category()
Checks whether the current or specified post has at least one of the specified categories.
Works for category
taxonomy only. Use has_term(), when you need to check a post for another taxonomy.
If no categories are provided for comparison, the function will check whether at least one category is assigned to a post.
The given categories are checked against the post's categories' term_ids, names and slugs. Categories given as integers will only be checked against the post's categories' term_ids.
If no categories are given, determines if post has any categories.
Uses: has_term()
Used By: in_category()
1 time — 0.003414 sec (very slow) | 50000 times — 0.84 sec (very fast) | PHP 7.1.5, WP 4.8.1
No Hooks.
Return
true|false
. True if the current post has any of the given categories (or any category, if no category specified). False otherwise.
Usage
has_category( $category, $post );
- $category(string|int|array)
- The category name/term_id/slug, or an array of them to check for.
Default: '' - $post(int|WP_Post)
- Post to check.
Default: current post
Examples
#1 Check if the post at least one specified category
$post_id = 6235; if( has_category( array(37,'history'), $post_id) ){ echo "Post with ID = $post_id is assignet to the category `37` or `history`"; }
Changelog
Since 3.1.0 | Introduced. |
has_category() has category code WP 6.7.1
function has_category( $category = '', $post = null ) { return has_term( $category, 'category', $post ); }