0

I know you can put custom page templates in the page-templates directory and WordPress will automatically detect them and make them selectable from a dropdown in the admin, but I would love to be able to further organize these in sub-directories...for example:

  • page-templates
    • some-template.php (works fine)
    • another-template.php (works fine)
    • products (sub-dir)
      • product-specific-template.php (not detected by default)
      • product-specific-template2.php (not detected by default)

Is there a way to tell WordPress to automatically detect all templates within page-templates and any subdirectories within page-templates ?

1
  • 1
    I don't believe so, but I suspect you could scan those folders yourself and filter the dropdown, I'm not sure of the filter to do that though, and it might cause compatibility issues particularly with 3rd party plugins that implement their own template system but still use the same wording to describe their feature, e.g. WooCommerce specific template files
    – Tom J Nowell
    Commented Sep 22, 2022 at 14:16

1 Answer 1

0

You should be able to do this with the theme_templates filter (see the get_page_templates() function). What you need is a function that walks through the sub-directories and returns all the page templates. Then you hook it into that filter.

You could create a function based on get_post_templates(), replacing the call to get_files() with a function that scans subdirectories as well.

This approach is a bit unstable, maybe, because you're copying core code that itself could change. Your code would be in the theme or plugin, but if the core version of get_post_templates() changed, you'd want to update your version of it as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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