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?
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.
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
example. So you could use this to load your template like this:
get_template_part( $template_fn_wo_ext, $template_fn_wo_ext );
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.