Getting the chosen template when iterating through pages

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();
       get_template_part('content');
    endwhile;
endif;

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x