Querying Custom Post Types in Your Theme Templates

Easy Content Types make it extremely easy to add new custom post types to your WordPress site. What is not always so easy is getting those post types to show up in your template files. This is mostly because a lot of themes do not support them very well. So I’m going to show you a few tricks to getting custom post types to show up in your template files the way you want them to.

Using WP_Query() in a Page Template

A lot of times you will want to show a list of custom post types on a particular page using a custom page template. When doing this, one of the easiest ways to show the post types, is to use WP_Query(). For this example, I’m going to assume that the custom post type list is being displayed in lieu of the regular page content. If you are simply including a list of post type entries at the bottom of your page content (or somewhere else), then consult Jeff Star’s article on 4 Ways to Loop WordPress.

So, to pull a list of custom post type entries in a page template, you can use query_posts(), like this:

<?php
if ( get_query_var('paged') ) $paged = get_query_var('paged');  
if ( get_query_var('page') ) $paged = get_query_var('page');
 
$query = new WP_Query( array( 'post_type' => 'books', 'paged' => $paged ) );
 
if ( $query->have_posts() ) : ?>
	<?php while ( $query->have_posts() ) : $query->the_post(); ?>	
		<div class="entry">
			<h2 class="title"><?php the_title(); ?></h2>
			<?php the_content(); ?>
		</div>
	<?php endwhile; wp_reset_postdata(); ?>
	<!-- show pagination here -->
<?php else : ?>
	<!-- show 404 error here -->
<?php endif; ?>

  • post_type – this is the post type you wish to display.
  • paged is required in order for pagination to work correctly