Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How do I set my custom loop to only show top-level posts? I have a hierarchical custom post type and the archive page shows both the parent and child posts.

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

This solution is based on some code by Justin Tadlock. pre_get_posts is called before WordPress gets the posts of the main loop. Basically, you test to see if the page is the archive of the post type and make sure post_parent hasn't been set. Then you set post_parent to 0, which is the default parent of top level posts. Easy as pie.

 <?php
    //pre_get_posts filter is called before WordPress gets posts
    add_filter( 'pre_get_posts', 'my_get_posts' );

    function my_get_posts( $query ) {
        //if page is an archive and post_parent is not set and post_type is the post type in question
        if ( is_archive() && false == $query->query_vars['post_parent'] &&  $query->query_vars['post_type'] == 'my_post_type')
            //set post_parent to 0, which is the default post_parent for top level posts
            $query->set( 'post_parent', 0 );
        return $query;
    }
    ?>
share|improve this answer
1  
Thanks @Manny Fleurmon that worked great! –  mattrepublic Sep 30 '11 at 17:11
add comment

You can just add post_parent=0 to your query

share|improve this answer
    
Yeah that's what I first thought, but it does not always work for some reason. –  mattrepublic Nov 11 '11 at 18:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.