Display WordPress CPT Posts In Current Category

This code will help you display custom post type posts that meet certain criteria.

On a current WordPress project I needed to display a list of specific posts.

The list of posts had two conditions:

  1. Be in the same category as the currently viewed post
  2. Be of a certain custom post type

This is the code that does the trick.

<ul id="catnav">
<?php
foreach( ( get_the_category() ) as $category ) {
$the_query = new WP_Query('category_name=' . $category->category_nicename . '&showposts=10&order=ASC&post_type="name_of_cpt_goes_here"');
while ($the_query->have_posts()) : $the_query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
<?php
}
?>
</ul>

Along the way I also messed around with two variations of the code.
This one displays posts that are the same Custom Post Type

<ul id="catnav">
<?php 
    query_posts(array( 
        'post_type' => 'name_of_cpt_goes_here'
    ) );  
?>
<?php while (have_posts()) : the_post(); ?>
        <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a><p><?php echo get_the_excerpt(); ?></p></li>     
<?php endwhile;?>
</ul>

Whereas this snippet will display the posts in the current category.

<ul id="catnav">
<?php
foreach( ( get_the_category() ) as $category ) {
 $current_category = new WP_Query('category_name=' . $category->category_nicename . '&showposts=5&order=ASC');
while ($current_category->have_posts()) : $current_category->the_post();
?>
            <li>
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
            </li>
<?php endwhile; ?>
<?php
}
?>
</ul>

Hire a WordPress Expert

Get hourly and project based theme customization, theme tweaks, and development help from world-class WordPress developers at Codeable. If you’re in Kelowna and need a custom website for your business visit our Kelowna Web Design page now to get started.