When I released Prospress last year, it used a contrived system for creating an index of auctions.
This was necessary as WordPress provided no standard method for creating an index page for custom post types. Now that 3.1 is just around the corner, this is all about to change.
Creating a Custom Post Type Archive
Let’s get semantics out-of-the-way first. It may be called an archive, for reasons hotly debated, but an archive can act as an index for your post type, just like the index.php file for blog posts.
Now, let’s take a look at the two simple steps for using a custom post type archive.
Step 1: Add an Archive Template to your Theme’s Folder
Create a new template to act as your custom post type’s archive. You can use any markup or style in your template. I start by copying the theme’s existing index.php file and then add any additional template tags or make any style changes from there.
You must name your template archive-{post-type}.php and store it in the base of your theme’s directory. For example, the auctions archive for Prospress is archive-auctions.php.
You only need to use a standard loop in the template. No need to run a new query for your custom post type – WordPress takes care of all that.
Step 2: Tell WordPress Your Post Type has an Archive
Now we have our template, we need to tell WordPress we want it to use a custom archive.
When registering your post type, set the has_archive flag in the $args array to true. This tells WordPress to generate the rewrite rules for your post type’s archive page.
For Prospress, this looks like so (abridged & paraphrased):
$args = array( 'public' => true, 'rewrite' => array( 'slug' => 'auctions' ), 'has_archive' => true, ); register_post_type( 'auctions', $args ); } add_action( 'init', 'register_auction_post_type' );
WordPress will now attempt to load archive-auctions.php for requests of the url example.com/auctions/.
A question on WordPress Answers also hints you can set the value of has_archive to create a custom rewrite instead of simply using true/false. I haven’t tested this though.
There you have it, a custom post type index or archive template. Told you it’s simple.
For further reading, check out:
- Justin Tadlock’s excellent tutorial on Custom Post Types.
- Mark McWilliams’ post on Custom Post Type Archives.
- The WordPress Codex function reference for register_post_type.
