The core WordPress function in_category()
is pretty handy but it’s also pretty basic.
in_category_extended()
is designed to extend the functionality of in_category()
in the following ways:
- test if the current post is assigned to the specified category OR any descendant categories
- return TRUE if you are viewing the specified category page OR any descendant category pages
Sure, you can do this a bunch of different ways, using multiple functions and code snippets, but I want a single boolean PHP function to use in my templates.
Example Usage
The main navigation consists of category tabs with on/off states.
If I’m viewing a post OR a category page which is related to the “development” category, then I want to apply a class="current"
to the development tab element, which I can then style accordingly with CSS.
class="<?= in_category_extended('development') ? 'current' : '' ?>" |
Function Definition
bool in_category_extended($category)
returns TRUE if the current webpage is related to the specified category
Function Parameters
$category
(mixed) (required) Category specified by ID (integer), or slug (string)
Function Code
This function has come in very handy for me – I hope you find it useful too!
function in_category_extended($category) { // easy out if (!(is_category() or is_single())) return false; // retrieve specified category (ID or slug) $obj_specified_category = is_numeric($category) ? get_category($category) : get_category_by_slug($category); if (empty($obj_specified_category->cat_ID)) return false; // we're viewing a category if (is_category()) { $current_category_ID = get_query_var('cat'); return ($obj_specified_category->cat_ID == $current_category_ID or cat_is_ancestor_of($obj_specified_category->cat_ID,$current_category_ID)); } // we're viewing a post else { global $wp_query; $obj_post = $wp_query->get_queried_object(); if (empty($obj_post->ID)) return false; if (in_category($obj_specified_category->cat_ID, $obj_post->ID)) return true; else return in_category(get_term_children($obj_specified_category->cat_ID, 'category'), $obj_post->ID); } } |
Since yesterday pm I try to do this – but I haven’t seen the wood for the trees;)
Today after a cup of coffee or two – I try a new search via Google and found your article:
you safe my weekend!
Thanks a lot for sharing your knowledge: it works like a charme!
kindly regards
Monika
No problem Monika – glad you found it useful 🙂