List Custom Post Types In Current Category

On a current WordPress poject 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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

1
2
3
4
5
6
7
8
9
10
<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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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>

Source: The Final Code Snippet Was Provided by Derek Barber