Custom Page Templates in Frontity? Current and very simple

Published on

Custom Page Templates are the mechanism available in WordPress to create global templates with specific designs that can be applied to one or multiple pages.

For example, if we need two types of pages on a site: one with a single column and another with two columns (main content and sidebar), a good option is to use the default page template, page.php, for the first one, and create a template, sidebar-page.php, for the second one. This way, for each new page, we can choose either design from the editor.

But what about Frontity, where the front-end is not generated from the PHP templates of the WordPress theme but from a React app? Well, Custom Page Templates are still the best option to work with multiple page layouts because they allow us to:

  • Select the desired layout from the page editor.
  • Assign them groups of ACF fields, extending the editing possibilities.
  • Display the assigned template file name in the REST API (and in the Frontity state), making it easier for Frontity to serve the correct layout in each case.

Now let's go through the complete process with a simple example.

Wordpress

We create a PHP file, for example, custom-page-template.php, with a comment at the beginning like the following:

Where "Template name:" is the tag that indicates to WordPress that this file is a page template, and "My Custom Page Template Name" is the name of our new template, which will appear in the template selector in the editor of each page.

Anything else to do? No, that's all on the WordPress side. 😎

However, to avoid errors (and some headaches), we must keep in mind that:

  • Custom templates only work if we have an index.php (it can be empty) in the root of our WordPress theme.
  • We should never use page- as a prefix in the file name because WordPress will interpret it as a specialized template intended to be applied only to a specific page of the site.

Frontity

We create three components:

  1. Page
  2. PageDefault
  3. PageTemplate

In the first one, we include a Switch that serves the second component, PageDefault, or the third one, PageTemplate, depending on the value of the template property in the page data from the Frontity state. If the published page in WordPress uses the default page template, this value will be empty, and if it uses a custom template, it will come with the name of the template file, custom-page-template.php in our case.

And finally, in the second and third components, we include the actual layouts for both types of pages.

Simple, isn't it?

If you have any questions, think something can be improved, or just want to say hello, you can reach me at hi@xulioze.com 😋