UPDATE: WordPress 3.1 now has support for index (archive) pages for custom post types, meaning that this code has outlived its usefulness. See Mark McWilliams’ post for the basic lowdown.
WordPress 3.0 finally gives us a ton of goodness out of the box for custom content types (post types in WP parlance). There’s a few extra things that I also wanted, and I keep adding new things. I have no intention to turn this into a plugin — only folks comfortable with a bit of code need apply.
- 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.
- Auto-generates appropriate admin UI labels if you don’t supply any yourself (otherwise WP defaults to “post” or “page”).
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 WP loads, 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).
- Initial release
- Added feed support in URL rewrites
- Removed redundant post_class code
- Removed redundant single post_type template code
- Introduced directory support for template files
- Use the newer, more robust labels array to set defaults
- Some code refactoring