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 WordPress Experts at Codeable.

The only WordPress exclusive freelancer platform that connects thousands of customers with the top WordPress freelance experts to work on projects of any size. 

Free estimate • No obligation to hire • 100% risk-free