Move theme templates to subfolder without losing page associations

I’m aware that templates can reside in a subfolder of a theme since 3.4.

My theme has been about for a while and all our templates reside in the theme directory. I’d like to tidy this up by adding them to subfolders, but simply moving them will result in all the pages losing their templates. Which would be a pain to rectify for 40 templated pages or so…

Is there a wordpress filter, hook or other method that could be used for checking template location? Which I can use to check for missing templates? google is turning up nothing useful.

Does anyone have any other wordpress based ideas?

(I’m aware I could try running a query to update template locations, but I’d rather not modify the DB directly if I can avoid it.)


Solutions Collecting From Web of "Move theme templates to subfolder without losing page associations"

You could hook the page_template filter and check if the current page has a _wp_page_template meta key. If it does, you can check if file_exists in the new templates location, then update_post_meta to append the new directory name.

One thing you can do is take advantage of the template hierarchy, wordpress conditional tag functions, and template parts.

Use index.php with conditional checks like is_archive(), is_page(), is_single(), etc. Then under each block, load a template part.


if ( is_archive() ) {
  if ( is_tag() ) {
    get_template_part( 'archives/', 'tag' );
  } elseif ( is_category() ) {
    get_template_part( 'archives/', 'category' );

get_template_part (linked above) allows you to load from a subdirectory. You can use the first argument to include a subdirectory if you include a trailing slash, and the second argument to use the php file’s base name. The advantage of this is that a child theme can override the template part using the same subfolder and filename.

Continue to use the other documented conditional tag functions and then you can load whatever templates you’d like. Plus, you can reuse template parts as needed.