[wp-hackers] template_redirect vs. single_template vs. other? (was $wp_rewrite->add_permstruct() vs. add_rewrite_rule())

Otto otto at ottodestruct.com
Thu Dec 10 16:10:19 UTC 2009


On Wed, Dec 9, 2009 at 8:42 PM, Mike Schinkel
<mikeschinkel at newclarity.net> wrote:
> That is really, really good and awfully useful, and couldn't find anywhere else.
> Add to the Codex somewhere?

Feel free to add it if you like. Might want to explain it better than I can. :)

>> In the case of pulling, say, custom post types, then it's a tad more
>> complicated.
>
> What about it is more complex?  I haven't found that yet.

For custom post types, in 2.8 there was no real support for them in the query.

2.9 adds that support, but doesn't create a rewrite tag for them. This
actually isn't difficult to do, you can use add_rewrite_tag to do it.
That will let you use the %post_type% as an identifier in a
permastruct. It also lets the post_type get defined in the query,
which (in 2.9) will cause the query to filter on your custom post
type.

Example (off the top of my head, might need editing):

add_rewrite_tag('%post_type%','.*');
$wp_query->add_permastruct('post-type','/type/%post_type%');

I think adding that on init should allow URLs of /type/custom to pull
up posts with "custom" in their post_type. You'd have to flush the
rewrite rules first, of course.

However, none of this gives you a special template hierarchy
automatically. These types of URLs would fall into the normal
"is_archive" hierarchy (the default hierarchy for "multiple posts to
display"), since there's no tests for your custom tag, unlike the
built-in tags. See http://codex.wordpress.org/Template_Hierarchy

So to create a special template hierarchy, you could either a) hook to
the template_redirect or b) hook to the archive_template. In either
case, you'd want to look at $wp_query->post_type and detect your
custom types there, in order to select the correct template to use in
the theme.

Just to pick one, if you were to hook to archive_template, you could
create a simple hierarchy like so:

add_filter('archive_template','my_hierarchy');
function my_hierarchy($template) {
  global $wp_query;
  if (empty($wp_query->post_type) return $template; // no post type,
don't bother going on
  $hierarchy = array ("{$wp_query->post_type}.php", "archive.php");
  return locate_template ($hierarchy);
}

This would let a custom post type (say, "custom") have its own theme
templates (say, "custom.php").

-Otto
Sent from Memphis, TN, United States


More information about the wp-hackers mailing list