WP Question: How to get page template name?


#1

Hi guys I run into a problem I want to list only pages that are created from template “Portfolio Template”. So my question is how can I check page template name?


#2

Really this is so hard? :stuck_out_tongue: I don’t know why but it is hard to find the answer on google… ;|


#3

http://codex.wordpress.org/Function_Reference/is_page_template - you can check by page template name


#4

If you have the page ID and you want to check the page template you can use

$template = get_post_meta( $id, '_wp_page_template', true );

If you’re querying those posts, I think you can do this:

$args = array(
	'post_type' => 'your-post-type', /* or just 'post' */
	'meta_query' => array(
		array(
			'key' => '_wp_page_template',
			'value' => 'portfolio.php', /* your template file name */
			'compare' => '='
		)
	)
 );
$query = get_posts( $args );

Haven’t tried it but it should work in theory :slight_smile:


#5

Here is my code. Actually, a whole bunch of solutions for various scenarios.

/********** GET PAGES BY PARAMS ************/

/– Get root parent of a page –/
function get_root_page($page_id)
{
global $wpdb;

$parent = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE post_type='page' AND ID = '$page_id'");

if ($parent == 0) 
	return $page_id;
else 
	return get_root_page($parent);

}

/– Get page name by ID –/
function get_page_name_by_ID($page_id)
{
global $wpdb;
$page_name = $wpdb->get_var(“SELECT post_title FROM $wpdb->posts WHERE ID = ‘$page_id’”);
return $page_name;
}

/– Get page ID by Page Template –/
function get_page_ID_by_page_template($template_name)
{
global $wpdb;
$page_ID = $wpdb->get_var(“SELECT post_id FROM $wpdb->postmeta WHERE meta_value = ‘$template_name’ AND meta_key = ‘_wp_page_template’”);
return $page_ID;
}

/* – Get page ID by Custom Field Value – */
function get_page_ID_by_custom_field_value($custom_field, $value)
{
global $wpdb;
$page_ID = $wpdb->get_var(“
SELECT wposts.ID
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = '$custom_field’
AND (wpostmeta.meta_value like ‘$value,%’ OR wpostmeta.meta_value like ‘%,$value,%’ OR wpostmeta.meta_value like ‘%,$value’ OR wpostmeta.meta_value = ‘$value’)
AND wposts.post_status = 'publish’
AND wposts.post_type = 'page’
LIMIT 0, 1”);

return $page_ID;

}
/*******************************************/


#6
sevenspark said

If you have the page ID and you want to check the page template you can use

$template = get_post_meta( $id, '_wp_page_template', true );

This line was the key! :slight_smile: Thanks guys for help.


#7
mpc said
sevenspark said

If you have the page ID and you want to check the page template you can use

$template = get_post_meta( $id, '_wp_page_template', true );

This line was the key! :slight_smile: Thanks guys for help.

You’re welcome :slight_smile: