Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress: Can you programmatically create page templates?

Tags:

wordpress

I am currently building a React/Redux theme for WordPress using the WordPress API. I need to add Page Templates to my theme. I can do this by creating almost empty files like:

<?php
/* Template Name: My Template */
?>

But I would like to create these 'Page Templates' programmatically.

The functionality I required is to be able to select a 'Page Template' inside the WordPress CMS and have this come down on the API. This functions as expected if the 'Page Templates' are created as above.

Is this possible?

like image 649
Adam Griffith Avatar asked Oct 28 '25 09:10

Adam Griffith


1 Answers

This can be achieved using the theme_page_templates filter.

CONST CUSTOM_PAGE_TEMPLATES = array(
  array('slug' => 'home', 'label' => 'Home'),
  array('slug' => 'content-page', 'label' => 'Content Page'),
  array('slug' => 'ordering', 'label' => 'Ordering'),
  array('slug' => 'reviews', 'label' => 'Reviews')
); 

/**
 * Add file-less page templates to the page template dropdown 
 */
add_filter('theme_page_templates', function($page_templates, $wp_theme, $post) {
  foreach(CUSTOM_PAGE_TEMPLATES as $template) {
    // Append if it doesn't already exists
    if (!isset($page_templates[$template['slug']])) {
      $page_templates[$template['slug']] = $template['label'];
    }
  }
  return $page_templates;
}, PHP_INT_MAX, 3);
like image 137
Adam Griffith Avatar answered Oct 31 '25 06:10

Adam Griffith