Posts Tagged ‘3.0’

Custom Post Types WordPress 3.0 with template archives

Thursday, April 15th, 2010

UPDATE: As of WP 3.1, custom post types archive pages are built in! (No doubt in response to this an other similar posts…) You just need to set the new ‘has_archive’ parameter to ‘true’ when registering the post type.

I’ve been playing around with the latest nightly betas of wordpress 3.0, especially the custom post type feature.  It looks great for what I want to do, but doesn’t exactly seem “ready”.  I’ve read various blogs and posts about custom post types trying to get a grips on making this lovely little feature do what I want.  Namely http://kovshenin.com/archives/extending-custom-post-types-in-wordpress-3-0/ and WordPress Codex, and this plugin http://wordpress.org/extend/plugins/cms-press/

I tried reading various tutorials on the web, and nothing really did what I wanted, so I’ve decided to make my own tutorial on how to create custom post types in wordpress 3.0 with archive pages.

The code within the plugin was finally what got me what I wanted.  So if your looking how to use custom post types in WordPress 3.0 and want to have your own archive template file with each of your custom post types then this post is for you.  I really JUST started to look into themeing and code in WordPress, so much of my work is borrowed from the sources listed about, and may not be the optimal way of doing things.  If you know of better/other ways to accomplish this, please pipe up in the comments, we’re all friends here.  I’ll try and explain the steps in detail so noobs like myself can follow along.

Here is what I wanted:

  1. A custom post type, we’ll say called “stories” that allows me to add stories in the wordpress backend.
  2. The URL of that custom post type to be an “archive” page of all the stories e.g. (www.domain.com/stories/)
  3. Each story to have its own structure like so (www.domain.com/stories/my-first-story/)

WordPress does numbers 1 and 3 automatically for you after you register the custom post type in your themes “functions.php” file.  This is done like so:

1st – Register the new Custom Post Type with wordpress

register_post_type('stories', array(
	'label' => __('Stories'),
	'singular_label' => __('Story'),
	'public' => true, // Allows it to be publicly queryable
	'show_ui' => true, // Displays the post time in the Admin Interface
	'_builtin' => false,
	'_edit_link' => 'post.php?post=%d',
	'capability_type' => 'post',
	'hierarchical' => false,
	'rewrite' => array("slug" => "stories"), // the slug for permalinks
	'supports' => array('title','editor','author','custom-fields') // What can this post type do
));

The code above will create a new link in your admin area where you can add the custom post type. If you don’t believe it, go ahead and add it to your functions.php file and check it out!

Number 2 turned out to be a LOT more tricky than I initially believed.  Before I get to the solution that worked for me, I’ll give a bit of background.

When you register a new custom post type in wordpress 3.0 it automatically creates rewrite rules for that post type.  (Which is what makes domain.com/stories/my-cool-story/) possible.  It doesn’t create any rewrite rules which would allow for (domain.com/stories/) to show an archive page.  If you tried to type that in, you would get a 404 not found.

The default rewrite rules that wordpress creates for your custom post types is like so:

[stories/[^/]+/attachment/([^/]+)/?$] => index.php?attachment=$matches[1]
[stories/[^/]+/attachment/([^/]+)/trackback/?$] => index.php?attachment=$matches[1]&tb=1
[stories/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?attachment=$matches[1]&feed=$matches[2]
[stories/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] => index.php?attachment=$matches[1]&feed=$matches[2]
[stories/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$] => index.php?attachment=$matches[1]&cpage=$matches[2]
[stories/([^/]+)/trackback/?$] => index.php?stories=$matches[1]&tb=1
[stories/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?stories=$matches[1]&feed=$matches[2]
[stories/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] => index.php?stories=$matches[1]&feed=$matches[2]
[stories/([^/]+)/page/?([0-9]{1,})/?$] => index.php?stories=$matches[1]&paged=$matches[2]
[stories/([^/]+)(/[0-9]+)?/?$] => index.php?stories=$matches[1]&page=$matches[2]
[stories/[^/]+/([^/]+)/?$] => index.php?attachment=$matches[1]
[stories/[^/]+/([^/]+)/trackback/?$] => index.php?attachment=$matches[1]&tb=1
[stories/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?attachment=$matches[1]&feed=$matches[2]
[stories/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] => index.php?attachment=$matches[1]&feed=$matches[2]
[stories/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$] => index.php?attachment=$matches[1]&cpage=$matches[2]

The current WordPress beta has the logic built into the templating system to look for a file called single-(custom-post-type).php for the custom post types “singular” pages.  So in my case the url (domain.com/stories/my-cool-story/) would be looking for a template file called “single-stories.php” in my themes folder.  If that file doesn’t exists it will use the regular single file, or eventually fall back on the “index.php” file.  Depends on how your theme is set up.

So the problem is that first, there are no rewrite rules for /stories/ to work.  Second, there is no logic to re-direct /stories/ to a template file which would show an “archive” of my stories.

The Solution.

2nd – Add new rewrite rules

After you’ve registered your custom post type, like I showed earlier in this post, we have to set up some re-write rules for our new shiny post type.  This is done like so.


add_new_rules();
function add_new_rules(){

	global $wp_rewrite;

	$rewrite_rules = $wp_rewrite->generate_rewrite_rules('stories/');
	$rewrite_rules['test/?$'] = 'index.php?paged=1';

	foreach($rewrite_rules as $regex => $redirect)
	{
		if(strpos($redirect, 'attachment=') === false)
			{
				$redirect .= '&post_type=stories';
			}
		if(0 < preg_match_all('@\$([0-9])@', $redirect, $matches))
			{
				for($i = 0; $i < count($matches[0]); $i++)
				{
					$redirect = str_replace($matches[0][$i], '$matches['.$matches[1][$i].']', $redirect);
				}
			}
		$wp_rewrite->add_rule($regex, $redirect, 'top');
	}

}

This bit of code I mostly took from the CMS Press plugin mentioned above. Check it out, it’s pretty sweet.

Which should produce the following NEW rewrite rules which are added to our already default rules that WordPress supplies us.  For a total of 19 rules/ custom post type.  (Someone could possibly speak to how many rules would be “acceptable” for a medium sized website in production, as I’m not really sure what constitutes “to many” rewrite rules when it comes to performance in WP…)

[stories/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?&feed=$matches[1]&post_type=stories
[stories/(feed|rdf|rss|rss2|atom)/?$] => index.php?&feed=$matches[1]&post_type=stories
[stories/page/?([0-9]{1,})/?$] => index.php?&paged=$matches[1]&post_type=stories
[stories/?$] => index.php?paged=1&post_type=stories

Notice that we added  the variable “post_type=stories” to each of our url’s that we rewrote.  This will allow us to redirect to our custom template in the next step.

Note: I’m not sure really where to hook this function so that it doesn’t make rewrite rules on each page load.  Really we only need to write the rules each time the permastructure changes, or we add a new post type, but I’m not sure how/where to do that.. Any ideas?

If your having troubles getting that rewrite rule to work, go and re-update your permalinks settings page.

3rd – Redirect requests on our new rules to our custom template files

So now we are going to add a hook into the system to over-ride the default templating system, because as mentioned in the background info section, wordpress doesn’t have this built in.

We essentially are checking to see if the variable “post_type=stories” exists in our query vars.  If it does, then we set up the feeds and trackbacks stuff that wordpress does, and we redirect to one of two theme files.

If the “name” variable isn’t in our query vars, then obviously the query is for the archive page, as the name variable only appears when we are requesting a single post.  So we redirect to a template file called “single-stories.php” if the name file does exists, (which is what wordpress would have done normally) and we re-direct to a template file called “single.php” if the name variable doesn’t exist.

Here’s my code:


	add_action("template_redirect",'template_redirect');
	function template_redirect()
	{
		global $wp;

		$muley_custom_types = array("stories");

		if (in_array($wp->query_vars["post_type"], $muley_custom_types))
		{
			if ( is_robots() ) :
				do_action('do_robots');
				return;
			elseif ( is_feed() ) :
				do_feed();
				return;
			elseif ( is_trackback() ) :
				include( ABSPATH . 'wp-trackback.php' );
				return;
			elseif($wp->query_vars["name"]):
				include(TEMPLATEPATH . "/single-".$wp->query_vars["post_type"].".php");
				die();
			else:
				include(TEMPLATEPATH . "/".$wp->query_vars["post_type"].".php");
				die();
			endif;

		}
	}

That way I can have custom 2 separate custom template files (post-type.php, and post-type-single) for each of my custom post types.

You would need to do that code for each of your custom post types, or write a little function to loop through an array of your custom post types and set them up automatically.

It would be nice if I could query wordpress for my custom post types and have it all be dynamic, but I haven’t looked into seeing if wordpress stores the custom post types in the DB.??

Anyway, that should get you started on hacking around with Custom Post Types.  I think that this should be the DEFAULT way that wordpress handles custom post types.  It seems to me logically that almost everyone is trying to do this by default with their wordpress installations that are running more “CMS” style instead of “blog” style.  Previously most everyone did this same sort of structure with categories and such with the Posts, but this way is much more organized if you ask me.

You can also add custom taxonomies (categories) for each of your custom post types should you so be inclined.  i.e. stories could be divided into fishing stories, hunting stories, hiking stories, etc.  however, we are focusing solely on post types in this tutorial.

Things to note:

-The title tags for your custom post type archives page won’t work.  I haven’t looked into how to fix this yet, as I have no idea how wordpress does titles, let alone for custom post types and custom rewrite rules.??  Any insights would be helpful.