Better View Handling in WordPress Themes

WordPress theme structure has largely stayed the same for the last 15 years. There are many great thing about the build in templating system in WordPress, such as the extensive and flexible hierarchy loading system, helpful conditional tags, and more.

However as themes become more complex the forced expectations of where template files are located can become frustrating. Looking at a theme’s root directory and finding a mix of stylesheets, template files, configuration files, project documentation, shell scripts, and more can be overwhelming.

WordPress is more flexible when you need to load template parts in your main template views. Functions such as get_template_part() and locate_template() are helpful in this way. You can define a custom path and bring in templates from outside of the root directory. But when you want to put your single.php template file in a new place things get a little more complicated.


View on GitHub

The last couple of themes I have built have implemented a system to filter WordPress’ default template location. I have found it to work very well; with the main drawback being a hardcoded list of potential files to filter. This list hasn’t been updated in more versions of WordPress than worth mentioning so I feel safe using it.

The method takes advantage of the {$type}_template_hierarchy filter. When a page loads the filter becomes page_template_hierarchy. WordPress uses this to create a list of potential files to load such as [ 'page-1.php', 'page-about.php', 'page.php' ]. So all we need to do is add our preferred location to this hierarchy. Since the list already exists we can simply loop through what WordPress has already chosen and add the same files back with our custom directory.

There are a few other checks in place to deal with child themes and some funkiness with index.php but that’s the basis of it.

Simply call it during runtime:

( new \BigBoxWC\WP_Template_Loader\Loader() )::watch();

The class also provides some static helpers to deal with manually loading template files to replace get_template_part() and locate_template() to provide more flexibility like passing variables between views.

Get the Library

Head over to GitHub to view installation and basic usage instructions.

Powering BigBox

Techniques like this and many more power the highly flexible and highly optimized BigBox WooCommerce theme.

Get BigBox Today →

Leave a Reply

Your email address will not be published. Required fields are marked *