I’ve been coding a WordPress theme using OOP PHP, node.js and Webpack, and between classes, node_modules, configuration files and WordPress template files my theme’s directory has become a bit messy…
Is there an easy way to move the theme’s template files to an app
subfolder without breaking the theme?
(I’ve found a similar question but it was asked in 2011, so hopefully something came up over time).
1 Answer
Out of the box WP relies on Template Hierarchy to resolve and load template. The default assumption is that (most) template are in the root of the theme and follow the naming conventions.
Placing template files elsewhere essentially requires rebuilding Template Hierarchy in your code with different assumptions. This used to be crazy inconvenient, but WP 4.7 introduced {$type}_template_hierarchy
hook, which makes it significantly easier.
As a personal aside I think native WP template simply doesn’t scale meaningfully to complex use cases. If there are enough templates to clutter the directory, then I would move to a different template engine (such as Twig) altogether. Of course that is hardly mainstream technique in WP development.
I have an example of template hierarchy override in my Meadow project for Twig integration, but same works for just changing up logic for PHP templates.