Reputation: 389
How do I check if the current archive page is for a subcategory of the parent category?
Let's say we have a parent category called "Economy" with 3 different subcategories. If I am on the archive page for one of it's subcategories, I want to implement this logic:
If (current archive page is a subcategory of the parent "Economy") {
//do something
}
How can I obtain this result?
Upvotes: 1
Views: 1973
Reputation: 14312
You can get the category of the current page using get_queried_object()
and then get the parent category id from it. You can then compare this id to the one you are looking for, or use the id to get the slug or name of the parent category to compare it instead.
1. Compare by ID
The shortest code is to compare the id of the parent category. (You can see the id of your "Economy" category in the admin)
$archive_cat = get_queried_object(); // get category for this archive page
// Check if the id of the category's parent is the term you want
if ($archive_cat->category_parent == 123) {
//do something
}
2. Compare by Slug
If you want to compare it to a particular parent slug, you need to get the parent category object first, then check it's slug
$archive_cat = get_queried_object(); // get category for this archive page
// get the parent category object using the parent id
$category_parent = get_term( $archive_cat->category_parent, 'category' );
// Check the slug of category's parent
if ($category_parent->slug == "ecomony") {
//do something
}
3. Compare by Name
You would usually use the id or slug in a comparison because they are alphanumeric and therefore easier to match. Names can contain spaces, punctuation, upper and lowercase etc which can complicate a comparison.
However if you have simple names and want to use those in the comparison, you can do it in a similar way as for the slug:
$archive_cat = get_queried_object(); // get category for this archive page
// get the parent category object using the parent id
$category_parent = get_term( $archive_cat->category_parent, 'category' );
// Check the name of category's parent
if ($category_parent->name== "Ecomony") {
//do something
}
Upvotes: 2