Methods to define a custom template in WordPress for any post type

Via theme.json or via php

Method 1: theme.json

Create a file in the <you_theme_root>/templates folder matching the custom template name in the code below. For example post-alt.html.

Place this inside the theme.json file at the root of your theme.

  "version": 2,
  "settings:: {},
  "customTemplates": [
      "name": "post-alt",
      "title": "Alt for post",
      "postTypes": ["post"]
      "name": "page-or-post-alt",
      "title": "Alt for page or post",
      "postTypes": ["page", "post"]
}Code language: PHP (php)

Method 2: Using PHP

Put a file in your theme containing the following (I also place this is my templates folder):

Template Name: My Custom PHP Template
Template Post Type: page
*/Code language: HTML, XML (xml)

My use case

I found that the php version was more useful for WP_Query as I could do something like the following (where $post_object_id is the filename of interest). This is filter for posts using the given page template.

$query_args['meta_query'] = [
    'key' => '_wp_page_template',
    'value' => 'templates/' . $post_object_id . '.php',
    'compare' => 'IN',
];Code language: PHP (php)

If you know how to do this using the first method I’d be interested to know how.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.