Including Custom Content Types in Your Theme

To create a single archive page for a custom content type, all you have to do is create another file in your theme directory, single-type.php. However, there is no built-in way to create a dedicated archive for a custom content type. To work around this, you must use a page template. Listing 12-18 shows an example archive template for Twenty Ten. Save this to your theme directory, then create a new page called Course Archives and choose this file as its page template (Figure 12-20).

Listing 12-18. A content archive page template for courses

Template Name: Custom Content Archive */

$wp_query = null; $wp_query = new WP_Query(); $wp_query->query('post_type=course'); $posts = null;

<div id="container">

<div id="content">

<?php if ($wp_query->have_posts() ) : while ($wp_query->have_posts() ) : $wp_query->the_post(); ?>

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-content">

<?php the_content(); ?> </div><!-- .entry-content --> </div><!-- #post-<?php the_ID(); ?> --> <?php endwhile; endif; ?>

</div><!-- #content --> </div><!-- #container -->

<?php get_sidebar(); ?> <?php get_footer(); ?>

Figure 12-20. Creating the custom content archive page

This template includes an alternative method of creating custom Loops that you haven't seen before. In this case, since you don't want to just modify the standard query—that would get posts as well as courses—you need to create a whole new query object, then call the have_posts() and the_post() functions as methods of this new object. (In fact, those functions always were methods of the $wp_query object, but like most things about the Loop, that part was invisible to you as long as you were working with the standard query.) Once you've set up the_post(), you can use all the usual content-related template tags.

The resulting archive page is shown in Figure 12-21.

Justin Tadlock has demonstrated how to add custom content types to a home page and main feed ( You can adapt his code, as shown in Listing 12-19, to show courses in the home page. This function and filter can go in the custom content plugin you created in Listing 12-12 or your theme's functions.php file.

Listing 12-19. Showing the course content type alongside posts on the home page add_filter( 'pre_get_posts', 'my_get_posts' );

$query->set( 'post_type', array( 'post', 'course' ) ); return $query;

Figure 12-21. The courses archive page

Was this article helpful?

0 0

Post a comment