WordPress Parent Category Recursive

·

·

On the long and curvy road of WordPress development such tasks are normal when you need to represent your posts (or categories) from different categories in a different way. If your website structure is limited to just two levels the generic cat_is_ancestor_of() function will serve you nicely. It takes two parameters. The first one is ID or object to check if this is the parent category and the second one is the child category. In this case if you want to find out if the category with slug «music» is the direct ancestor of current category you can use the following bit:

cat_is_ancestor_of(get_cat_id(‹music›), get_query_var(‹cat›))

Of course you can use the direct IDs for any of parameters. This code can be modified to find out if any of the categories your post belongs to have some specific ancestor.

foreach(get_the_category() as $category){

if(cat_is_ancestor_of(get_cat_id(‹music›), $category->term_id)){

}

}

Here we are using another generic WordPress function get_the_category() which returns an array of objects, one object for each category assigned to the post. It takes one optional parameter: the post ID, which defaults to current post ID.

Unfortunately WordPress does not have a function in its arsenal to walk through whole directory tree and find out if our post or category have some specific ancestor somewhere deeper then one level down. In this case you can use the following custom function I wrote. I took the source code of WordPress get_category_parents() function as the origin. Here is the result:

function cat_is_ancestor_of_recursive($ancestor_id, $of_id, $visited = array()){

$visited[] = $of_id;
$parent = &get_category($of_id);
if(is_wp_error($parent)){

return false;

}elseif($parent->term_id == $ancestor_id){

return true;

}elseif($parent->parent && $parent->parent != $parent->term_id && !in_array($parent->parent, $visited)){

return cat_is_ancestor_of_recursive($ancestor_id, $parent->parent, $visited);

}

}

It takes absolutely the same parameters as cat_is_ancestor_of() but walks the complete tree recursively. The third parameter is for internal use and does not have to be passed when calling the function. It holds the array of categories already checked to prevent infinite loops.


Kategorien

Beliebte Tags

AI blockchain ecommerce ethics events Magento marketing Metaverse NFTs privacy security SEO shopify socialmedia update WooCommerce WordPress


Der englischsprachige Podcast von Openstream. Discover how memes, AI, and digital culture shape our world, challenge norms, and redefine what it means to be human.

spotify-podcast-badge
Listen on Apple Podcast