Reputation: 357
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?
Upvotes: 4
Views: 2820
Reputation: 357
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);
Upvotes: 2