0

Is there a way to make a condition for posts belonging to any sub-categories of a given parent category? Here is an example, assuming the following category structure:

  • News
  • FAQ
    • 1) Installing
    • 2) Using, etc.
  • Other
if ( has_category( 'FAQ' ) ) { 
    echo "This page has been updated for Quick Access Popup v10.";
}
else {
    echo "This page has NOT been updated for Quick Access Popup v10 yet.";
}

The has_category() condition includes only posts that are in the category 'FAQ' itself, but not those in its subcategories. I know I could use an array and list every categories but this is not convenient and need to be maintained when subcategories are added, removed, etc.

The has_category() doc says nothing about parent categories (https://developer.wordpress.org/reference/functions/has_category/)

Thanks.

0

To do what you want, you'll need to get a list of all the child categories of the category you want, and then check those. But you don't need to write that list manually. You can use get_term_children() to get the IDs of the child and grandchild categories:

$cat_id   = get_cat_ID( 'FAQ' );
$children = get_term_children( $cat_id, 'category' );

if ( has_category( $cat_id ) || has_category( $children ) ) {

}
| improve this answer | |
  • Thanks @Jacob Peattie. This is exactly what I needed. I changed it a bit because I want the snippet to be displayed only in the post of the children categories but also in the children categories pages themselves: if ( is_category( $children ) || has_category( $children ) ) { ... } – JnLlnd Nov 13 '19 at 4:26
  • You can just remove is_category( $children ) || if you want to do that. – Jacob Peattie Nov 13 '19 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.