Is post category(ies) a child of parent category?
-
I’ve been struggling to figure out how to do this. Seems like such a simple task. I have a hierarchy of categories X levels deep, and I want to render recent posts from any category that is child of a more general category… and here’s the function to get things started. This function will take a post ID, and the parent category you want to see if it is a child of…
(This way it is more dynamic than hardcoding (is_category(1) || is_category(2) etc. etc.)
function post_child_of_cat($child_post_id, $parent_cat_id) { $cat_array = wp_get_post_categories($child_post_id); foreach ($cat_array as $category) { if (cat_is_ancestor_of((int)$parent_cat_id, (int)$category)) { return true; } } return false; }
So, I have a category like so
Fruits > Green > Apples
And I want output recent posts from any category under fruits on any of the apples pages… lets assume the fruit category has a category id of 69. I want to put this code in the template that the posts use, inside the loop,
for example, put this in the loop in single.php..
if (post_child_of_cat($post->ID, 69)) { // do whatever you want here... }
- The topic ‘Is post category(ies) a child of parent category?’ is closed to new replies.