WordPress at a glance

has_category() WP 3.1.0

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.

Is the basis for: in_category()
Works based on: has_term()
✈ 1 time = 0.003414s = very slow | 50000 times = 0.84s = 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).

Usage

has_category( $category, $post );
$category(string/int/array)
The category name/term_id/slug or array of them to check for.
Default: ''
$post(int/object)
Post to check instead of the current post.
Default: null

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`";
}

Code of has_category: wp-includes/category-template.php VER 5.0.1

<?php
function has_category( $category = '', $post = null ) {
	return has_term( $category, 'category', $post );
}

Related Functions

From tag: Conditional tags (all)

More from category: For posts

No comments
    Hello, !     Log In . Register