1

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.

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.

  • 1
    My pleasure, besides you you asked nicely on your last question, that always helps:) @TauSand – Nicolai Aug 31 '14 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.