On the back of my hooks article last week, here’s another potentially useful WordPress trick I’ve picked up: detecting the current page template.
No SQL required
The beauty of the WordPress API is that in most situations, you can pull the values you need from the database without writing lines of SQL code. For example,
global $post;
get_post_meta($post->ID,'_wp_page_template',true);
This returns the template being used by the current page—for example, running it on my archives page would return the value archives.php, while doing it on my about page would return default. The function get_post_meta is documented in the Codex, but basically, it grabs some data from the wp_postmeta table of the database, which is used to store custom fields, including the post template.
A trip through postmeta land
By using the WordPress-generated $post variable, we avoid having to talk to the database directly; $post->ID returns the ID value of the current post, which can then be checked against the records in wp_postmeta. Since we want to return the page’s template, our second argument calls the key _wp_page_template, so the function will only return values with that key.
By default, the function returns an array, but by setting the third argument to true we can make it return a single result (the first one, although it’s pretty unlikely that a page has two _wp_page_template values. Obviously this technique can be extended to return the values for other custom fields, but I’ll leave that as an exercise for the reader.
The why of it
This trick could be useful for any number of things—I’m using it in Tarski to check whether a given page is an archives page, and to include or exclude certain things based on the result.
Obviously if I were just doing the include directly in the archives template, this wouldn’t be a problem, but since I’m actually calling a hook that’s present in a number of other templates, there’s no way I can tell in advance whether a given page is an archives page or not. In effect, I’m putting the coding burden onto my actions and filters, so as to not impose an overly restrictive system on end-users who might want to do something entirely different.
Coda
As a non-programmer myself, I’m always trying to work out how to do fairly simple things in WordPress. If people are interested, I could carry on writing up these code tips, so let me know what you think in the comments.
Amendment, 5th November 2007
If you’re on the WordPress trunk, instead of bothering with all this malarky just use the is_page_template function which was added in revision 6228. It will be in the 2.4 release when that comes out, and it uses essentially the same technique as I’ve described here, albeit with—as you’d expect—much more complete error handling.
Very interesting code tips e.g. WP hooks. Keep on, as it’s easy to understand via your write up.
~ milo #