For the most part, the file-structure of WordPress themes is pretty logical, however, there are aspects which keep bothering me about the Template Hierarchy:
- home.php – I understand the historic reason why the blog’s main archive is named
home.php, but every time I make a new theme, I wonder why such an illogical naming convention still persists. It’s confusing to new users, and simply serves to continue the flawed narrative that the blog is the core of the WordPress experience.
- front-page.php overrides page templates – This is particularly frustrating when a parent theme includes a front-page.php file, as there is no way to offer template file choices in the child theme, without modifying the parent.
- Custom URL routing is complicated – Sometimes I need a specific url to run my own code, outside of a traditional template file. Often, I’m stuck defining custom rewrite rules and template redirects, or jamming my code into shortcodes and custom templates.
Being a developer. I decided to fix these perceived flaws.
Improved Template Hierarchy is a plugin that makes three crucial changes to the structure of theme files.
- To improve clarity of purpose,
home.phphas been aliased to
blog.php. To preserve compatibility with existing themes,
home.phpcan still be used, but if a theme contains a
blog.phpfile, it will override
home.phpin all instances.
- Custom page template settings will now override the
front-page.phptemplate, like they do with all other pages. Since the user is presented with the option of using a custom page template for this page, it should be assumed that this choice will change the appearance of the front page. Leaving the front page template set to “Default” will fall back to using the traditional
front-page.phpfile, if present.
- You can create your own “path template” files, that are similar to page templates, but define custom url routes for your site.To declare a custom path template, simply create a file with the following header comment:
Custom Path: url/path/here
Parse Subdirectories: true
In the example above, requests made to
http://domain.com/url/path/here/will be routed to this template file. Furthermore, the optional
Parse Subdirectoriestag indicates that child paths like
http://domain.com/url/path/here/example/pathwill also be routed to this script. This simplifies the process of building out complicated rewrite rules and redirects.To ensure that control remains with the user, in the default configuration, if a user creates a post or page at the address specified in a template file, the post or page will take precedence over the custom route. However, the template can be given precedence by using the following snippet:
add_filter( 'force_custom_path_templates', __return_true );
The resulting template hierarchy (not including custom path templates) looks like this:
And here is the plugin code. Let me know what you think of this proposal, in the comments.