1

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.)

Thanks!

  • My guess would be that to achieve this you'd have to modify wordpress core. Which isn't advised. However, if you take a look at wp-admin\includes\theme.php and find a function called get_page_template() and also wp-includes\class-wp-theme.php and look at the class method called get_page_templates() you may be able to find a method around this by understanding how the templates are generated. But in all honesty I believe doing it via a DB query is the best answer – Craig Pearson Jan 29 '15 at 18:45
3

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.

  • Got it working with a little RecursiveDirectoryIterator magic to grab the new location. thanks a bunch for the tips – josh Jan 30 '15 at 14:58
0

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.

E.g.

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.

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.