Post Pic

How to check if a page template is active

Conditionnal tags are very useful when you need to know if you’re on a post, page, homepage, etc. But how to know if you’re are on a specific page template? Nothing hard, just use the following recipe.

Paste the following on your functions.php file:

function is_pagetemplate_active($pagetemplate = '') {
	global $wpdb;
	$sql = "select meta_key from $wpdb->postmeta where meta_key like '_wp_page_template' and meta_value like '" . $pagetemplate . "'";
	$result = $wpdb->query($sql);
	if ($result) {
		return TRUE;
	} else {
		return FALSE;
	}
}

Once done, you can call the function like this:

if (is_pagetemplate_active("Archives")) {
  // The "Archives" page template is active
} else {
  // The "Archives" page template is NOT active
}

Credits goes to Wupper Piraten for this cool recipe!

5 Responses

Dec 28 2009 09:52

Nice tips :)
I think the code will be more tidy if we uppercase the SQL keyword.
$sql = “SELECT meta_key FROM $wpdb->postmeta WHERE meta_key LIKE ‘_wp_page_template’ AND meta_value LIKE ‘” . $pagetemplate . “‘”;

Dec 29 2009 01:42

Doesn’t :

is_page_template(‘templatename.php’)

Provide this functionality already?

Ref:http://codex.wordpress.org/Function_Reference/is_page_template

Dec 29 2009 03:55

I agree with Thomas Carter. This functionality is already built into WordPress, with is_page_template(‘template.php’);

Jan 15 2010 21:09

With is_page_template() you have to know the name of the template page. What if you want to evaluate whether or not a page is using any template? Is there a way to do that? Something like has_page_template() ?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required