Skip to content

Instantly share code, notes, and snippets.

@vwasteels
Last active June 23, 2022 10:04
Show Gist options
  • Save vwasteels/0249cd8c6c36c3932e8ef82bba0213a4 to your computer and use it in GitHub Desktop.
Save vwasteels/0249cd8c6c36c3932e8ef82bba0213a4 to your computer and use it in GitHub Desktop.
WP : page templates in sub folders
<?php
/* Pages templates in subfolders */
/*
This will add ./pages/my-custom-folder/*.php templates
if no "Template Name: My name" is specified, name will be : "Subfolder > Filename"
*/
add_filter('theme_page_templates', function($post_templates) {
$directories = glob(get_template_directory() . '/pages/*' , GLOB_ONLYDIR);
foreach ($directories as $dir) {
$templates = glob($dir.'/*.php');
foreach ($templates as $template) {
if (preg_match('|Template'.' '.'Name: (.*)$|mi', file_get_contents($template), $name)) {
$name = $name[1];
} else {
$name = ucfirst(basename($dir)) .' > '. ucfirst(pathinfo($template)['filename']);
}
$post_templates['/pages/'.basename($dir).'/'.basename($template)] = $name;
}
}
return $post_templates;
});
@vwasteels
Copy link
Author

vwasteels commented Jun 23, 2022

note : in the preg_match method, the Template'.' '.'Name prevents this piece of code of being detected itself as a template with the name : (.*)$|mi', file_get_contents($template), $name)) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment