Getting the chosen template when iterating through pages

The question:

Im trying print all the pages on a wordpress site. Im using the following code:

$args = array( 'post_type' => 'page');
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();

This works fine, but i want each page to be rendered with the template chosen by the admin in the admin menu. Is it possible to fetch the template name so i can provide it to the get_template_part?

Best regards.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

The filename of the template chosen for pages is saved in a post meta field called _wp_page_template, which you can get e.g. like this:

$template_filename = get_post_meta( get_the_ID(), '_wp_page_template', true );

Now you have a file name like example-template.php, with it you can determine which template to load, if you named it right, so you could e.g. do:

$template_fn_wo_ext = substr( $template_filename, 0, -4 );

Which does remove the last four characters, so you get example-template, now you could do:

$template_fn_parts = explode( '-', $template_fn_wo_ext );

Which gives you back an array with the string parts, splited at the -, e.g. $template_fn_wo_ext[0] contains example. So you could use this to load your template like this:

get_template_part( $template_fn_wo_ext[0], $template_fn_wo_ext[1] );

This should get you an idea and started, but it is just exemplary, so do the fine tuning and fitting it to your needs is likely needed.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment