In reality, determining this is quite simple. For example, if we are on an archive page (where hooks like is_archive, is_tag, etc. are triggered), we can use the following approach:
add_action('wp', function()
{
$Term = get_queried_object();
if(is_a($Term, 'WP_Term'))
{
if($Term -> parent > 0)
{
echo 'Category, tag, or term is a child of';
}
}
});The get_queried_object() function contains dynamic data — that is, data depending on the page we’re currently viewing. If it’s a single post page, the function returns a WP_Post object with post data. If it’s an archive page (for a category, term, or tag), get_queried_object() will return a WP_Term object. In some cases, it may return a post_type object.
Back to the code above — using the parent property of the term, we can determine whether the current term is assigned under another one. If parent equals zero, the term is at the root level. If parent is greater than zero, the term is nested inside another and is considered a child.
That’s the case when we are already on a category page, etc. But what if we want to check the parent of an arbitrary term — for example, by its ID or slug?
For that, we can use the get_term_by() function.
This is a helpful function that lets us retrieve term data using its id / slug / name / term_taxonomy_id. For example, to get a term by ID:
$Term = get_term_by(‘id’, 123, ‘category’);
As you’ve likely guessed, the third argument is the name of the taxonomy the term belongs to.
Likewise, you can get a term by slug:
$Term = get_term_by(‘slug’, ‘test-term’, ‘category’);
Once we’ve retrieved the term object, we can check its type and parent value:
if(is_a($Term, 'WP_Term'))
{
if($Term -> parent > 0)
{
echo 'Category, tag, or term is a child of';
}
}That’s it! 🙂
