How can I return a child category from a post with multiple categories in WordPress?

I’m returning a post that has multiple categories assigned to it (WordPress), and one category has a child category selected as well.

 - Cat 1
 - Cat 2
 - Cat 3
 -    Child Cat 1

There would be multiple categories under Cat 3, but only one assigned to this post. I know what the ID of Cat 3 is (this is a category specific post), but I don’t know how to return just the selected child cat ID of cat 3.

Read More

My thought was to use get_categories, and I could pass in the static Cat 3 ID, but it won’t know what category is selected from the post.

Brownie points if you can tell me how to format the output like this: 'cat=2' so I can use it in my query as an argument.

Any help would be appreciated.

Thanks!

Related posts

Leave a Reply

1 comment

  1. Ok, I figured it out. I was using the wrong function.

    I should have used wp_get_post_categories

        <?php 
    $catString = "cat=";
    // this is the ID of the Parent category, might change per db
    $parent = 6;
    $cats = wp_get_post_categories($post->ID);
    foreach($cats as $cat) {
        if(cat_is_ancestor_of( $parent , $cat ))
            $catString .= $cat . ",";
    }
    ?>
    

    And the output is cat=1,2,3, which is still accepted into the query with the , on the end.