Getting the chosen template when iterating through pages

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)