Support » Themes and Templates » Pull Child category but not Parent into posts query

  • Im trying to pull in child categories of a master category in query posts. Does anyone know how to do this?

    Im using this <?php the_category() ?>, but its pulling in both the parent and child and thats not what I want!

    Please help!


Viewing 7 replies - 1 through 7 (of 7 total)
  • How are you using the_category() here exactly?

    It would help to know *where* you expect to collect the child categories from. Is this on category queries, or on single post pages? Or something altogether else?

    on category queries. Im trying to generate a list of all the children of a category and their posts.

    well basically it would look something like this:
    child-category | post title

    and it would loop through everything within the parent category – but only show the children not the parents…

    Is that do-able?

    I’m always tempted to answer that last question with:

    Of course it is. But are you up to the task? ;)

    Actually it’s not that hard, since what you’re asking for is a simple way to call or query any child categories, and set post loops for each of these (if I’m reading you correctly).

    For the child category ‘call’ we can make use of the category cache:

    <?php $categories = get_categories(); ?>

    From here you can test on whether the current category ($cat) is a parent to any others:

    foreach( $categories as $category ) :
    	if( $cat == $category->parent ) :
    ~do your stuff here~
    <?php endif; endforeach; ?>

    $category will hold the values you’ll need for setting up your queries and such (in that ‘do your stuff here’ portion). Couple important properties for that:

    $category->name = Category name or title
    $category->term_id = Numeric category ID

    Yeah, Im up for the task.

    So that will pull in the child categories?

    Im confused as to what this statement means??
    if( $cat == $category->parent ) :

    if( $cat == $category->parent ) :

    $cat is a global variable that’s available when on a category query. When viewing the parent category for one or more children, the if statement will evaluate as true, as it compares $cat to the parent category value for each child category ($category->parent).

    Ok so here is my code:

    $myposts = get_posts('category=8');
    foreach($myposts as $post) :
    	<td><?php the_title(); ?></td>
    	<td> Single Category Child Goes Here</td>
    <?php endforeach; ?>

    Im looping through and I want to show the title – child category for each.

    In category 8 – I have about 20 sub-categories. Does this make sense?

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Pull Child category but not Parent into posts query’ is closed to new replies.