While development on WordPress 3.1 is still ongoing and we’ll probably not see the final release until nearer the end of the year, I thought I’d let you know about a cool new addition to Custom Post Types that Andrew Nacin (Core Developer) worked on!
Little Background Info
Around 5 months ago #13818 was opened requesting an Index/Archive option for Custom Post Types because the way WordPress works meant that /post-type/ would just 404 on you although /post-type/wordpress-rocks/ worked just fine.
Similar could be said about Custom Taxonomies and how they function which I brought up back in February on the WP-Hackers Mailing List – I don’t think I was popular in the community that month for sure? While it’d be a nice addition I know many would like (and shut me up) I have been informed more than once it’ll not happen!
Now For Some Code
If you’re new to Custom Post Types and the register_post_type(); function then make sure to check out an in-depth article Justin Tadlock wrote on the subject, I recommend you read it anyway! :)
In our functions.php file lets setup a basic Projects Post Type with the Archive active.
add_action( 'init', 'mcw_projects_post_type' );
function mcw_projects_post_type() {
register_post_type( 'projects', array(
'labels' => array(
'name' => __('Projects'),
'singular_name' => __('Project')
),
'public' => true,
'show_ui' => true,
'rewrite' => array(
'slug' => 'project',
'with_front' => false
),
'has_archive' => true
) );
}
We’re looking at the has_archive argument which has been set to true which will turn on the Archive for this particular Custom Post Type, normally it would default to false though! — But we can take that a step further because when it’s set to true it’ll fallback to the value in the slug argument. So here that would make it site.com/project/ which just wouldn’t look quite right!
'has_archive' => 'projects'
All we did was substitute true with projects which therefore shows site.com/projects/ as being home instead. Now we know we can do that, we can do all sorts of things (get creative), we don’t need to keep it in line with our Projects Post Type.
'has_archive' => 'work'
Thinking outside-the-box gives you site.com/work/ which is different, the option is yours!
What Else Might I Need To Know
A new archive-{$post_type}.php template was introduced although it will fallback to archive.php if it can’t find the appropriate template for the job. So for our Projects Post Type, as projects happens to be the value we used for the Custom Post Type, we’d call our template archive-projects.php — Similar to if we used the portfolio value for a Portfolio Post Type we’d end up calling our template archive-portfolio.php and so on.
If you get a 404 error when trying to view the Custom Post Type Archive then simply visit Settings > Permalink which will flush your rewrite rules for you, it’s as simple as that, and there we have it!