Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress WordPress Theme Development Custom Post Type Templates in WordPress The WP_Query Function

Aron Macarow
Aron Macarow
2,615 Points

How to display custom posts of only one category?

I'm trying to display one category at a time using my category.php file for custom post type 'portfolio'.

This code gives me the category (in this case, a year like "2016"), but doesn't display any posts attached to that category. I have a feeling this is because I'm not using WP_query to specifically search post_type='porfolio' ... but when I add that, all of the portfolio posts show up instead of just the ones in the category selected:

<?php single_cat_title(); ?>

<div class="grand-works">


            <?php if (have_posts()) : ?>


         <?php while (have_posts()) : the_post(); ?>

                <?php get_template_part( 'content', 'works' ); ?>

            <?php endwhile; endif; // end of the loop. ?>

        <?php wp_reset_postdata(); ?>

</div>

Help?

1 Answer

Aron Macarow
Aron Macarow
2,615 Points

For anyone having trouble, I finally figured this out minutes ago after hours of reading:

<?php single_cat_title(); ?> <div class="grand-works">

<?php $current_category = single_cat_title("", false); ?>

<?php

        // The Arguments
        $args = array(
            'post_type' => 'portfolio', 
            'category_name'  => $current_category
        );  

        // The Query
        $the_query = new WP_Query( $args ); ?>

        <?php

        // If we have the posts...
        if ( $the_query->have_posts() ) : ?>

        <!-- Start the loop the loop --> 
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                <?php get_template_part( 'content', 'works' ); ?>

            <?php endwhile; endif; // end of the loop. ?>

        <?php wp_reset_postdata(); ?>

</div>