NOTE: I’ve moved this into its own project page, where you can now find the download link and leave comments. This post will no longer be updated and comments are now off.
WordPress 3.0 is almost ready for prime-time, and with it full support for custom post types. You can read about the technical details of adding a custom post type, or why you should use them. The WP team have done a great job with bringing this functionality into the upcoming 3.0 release, but one thing that’s puzzled me is (current) lack of good support for 1) custom URLs for that particular post type only (something like http://yourdomain.com/movies ) and 2) custom templates for that post type. (I’ll be using this to move portfolio items to a “portfolio” post type.)
But, that’s nothing a little code can’t fix. With the helper class I’ve made, the following is possible:
- Custom URLs for a landing page for your post type, with full pagination & feed support. (eg http://yourdomain.com/movies/, http://yourdomain.com/movies/page/2/, http://yourdomain.com/movies/feed/ )
- Custom landing page templates: if you registered “movie” as your post type, you can use
movie.phpin your theme directory (falls back to
index.phpif they don’t exist)
- Custom single page templates: WP already looks for
single-movie.php(and falls back to
single.php). This function allows you to use
movie/single.php— great alongside
movie/index.phpfor better theme organization.
- adds classes to
post_class()for that post type.
After including the
SD_Register_Post_Type class and the helper function
sd_register_post_type(), all you need in your functions.php file (or wherever you choose to run this) is the following line:
sd_register_post_type( 'movie' );
That’s it. Call it again with a new argument for another post type. Repeat as many times as you need post types. I’ve set good default arguments to pass to
register_post_type(), but you can override them with your own. (Read more about the $args here, here and here.)
sd_register_post_type( 'movie', $args_array );
Also, grammar pedants know that adding an “s” suffix is not appropriate for all plurals. In the case of post type “movie”, our URL landing structure is http://yourdomain.com/movies, which works fine. But, for irregular plurals, the function accepts an optional third argument:
sd_register_post_type( 'person', $args_array, 'people' );
The above URL structure would then be http://yourdomain.com/people for the post_type “person”.
One note that’s very, very important: your custom URLs won’t work until you go to Options → Permalink in wp-admin and re-save your current URL structure. This will flush WP’s current URL structure and add our new rewrite rules. This is computationally expensive and you don’t want it happening every time, which is why I’m leaving it as a manual operation. You’ll only need to do it once (or after changing the third plural argument).