Last active
June 23, 2022 10:04
-
-
Save vwasteels/0249cd8c6c36c3932e8ef82bba0213a4 to your computer and use it in GitHub Desktop.
WP : page templates in sub folders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note : in the
preg_match
method, theTemplate'.' '.'Name
prevents this piece of code of being detected itself as a template with the name :(.*)$|mi', file_get_contents($template), $name)) {