Automatically Apply Custom Page Templates

A lot of WordPress themes include custom page templates. These can be used to create a different layout than the standard page.php file. Originally this was used (and is still a valid use-case) to provide just a marginally different layout such as removing the page’s sidebar.

As the WordPress ecosystem grew so did the use cases for custom page layouts. Separately styled pages for eCommerce cart & checkout pages, account pages, contact pages, and more became very common. The developer documentation for page templates suggests that these one-time use templates should not be given the traditional PHP comment header to avoid having them appear in the “Page Attributes” meta box.

The WordPress template hierarchy allows for a file to be created named page-checkout.php that is loaded when a page with the slug of checkout is being viewed. This is fine for internal usage but a distributed theme needs to support dynamic permalink options. Since WooCommerce can programmatically determine which page is being viewed this information cab be used to update which template file should be loaded.

In a previous article I wrote about expanding the template hierarchy to allows views to be placed in a different directory. The same technique is used here:

Now when is_checkout() is true, the template hierarchy will automatically be updated to:

With this technique the one-off page templates can be applied without taking up space in the Page Attribute meta box — leaving room for templates that are meant to be used more than once.

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 *