Get template name in WordPress

Generating the template name isn’t really a big deal, globally it’s available via echo get_option('current_page_template'). But in this case, when I was generating a slideshow of multiple pages, I needed to pass the slideshow query to it. So I had to write up my own for functions.php.


function get_template_name($query1) { 
	$template_name = get_post_meta( $query1->post->ID, '_wp_page_template', true ); 
	$length = strlen($template_name) - 4;
	if (strpos($template_name, '.php')) { 
		$template_name = substr($template_name, 0, $length);
		return $template_name;
	} else { 
		return $template_name;
	}
};

Call it after the while condition and it will generate the template name for each post (ie: echo get_template_name($query1)) The template name is stored like a simple meta value and includes the .php extension. So this will check for that to strip it out, otherwise will return ‘default.’

Why is this necessary for my slideshow? Well, some pages are to be laid out differently, this allows the CSS to make multiple slides of differing layouts.

More Posts

Donate

Hey was this useful? Please consider tipping or subscribing as a member. Even just $1 or $5 can help me improve this content and keep it ad-free.