I am working on a site that will have up to 30 templates in it.
I don’t want to have all those templates at the root of my theme folder cluttering up everything.
I know how I can modify the get_page_templates()
function in the file wp-admin/includes/theme.php
to make it scan sub dirs in my theme folder. But I do not want to change core files manually – how can I apply a filter to get_page_templates()
with a filter that I put in functions.php
?
As the code you see below is my first attempt at this but it doesn´t work yet when I put the code inside function.php
.
I can however put these changes into the core file wp-admin/includes/theme.php
but that is not good practice and should always be avoided right, as auto update can wipe it out.
function get_page_templates_override()
{
$themes = get_themes();
$theme = get_current_theme();
$templates = $themes[$theme]['Template Files'];
$page_templates = array();
if ( is_array( $templates ) ) {
$base = array( trailingslashit(get_template_directory()), trailingslashit(get_stylesheet_directory()) );
foreach ( $templates as $template ) {
$basename = str_replace($base, '', $template);
// modifide this by commenting it out so that sub dirs arent blocked
// if ( false !== strpos($basename, '/') )
// continue;
// modified this with FILE_USE_INCLUDE_PATH so sub dirs get scanned
$template_data = implode( '', file( $template, FILE_USE_INCLUDE_PATH ));
$name = '';
if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) )
$name = _cleanup_header_comment($name[1]);
if ( !empty( $name ) ) {
$page_templates[trim( $name )] = $basename;
}
}
}
return $page_templates;
}
add_filter('get_page_templates','get_page_templates_override', 1);
That part is extremely rigid, see this question about loading page templates from plugin directory.
With current state of related code I would not bother spending time on this. Especially since you want it for convenience (putting template in sub-directories) and not functionality (like loading from plugin folder).
There are a couple of tickets on this: #13265 and #11216.
Also, it looks less cluttered if you prefix each template with a fixed string:
etc.
It’s worth mentioning that as of WP 3.4 (nearly a year ago) it is now possible to place template files into a directory below the theme root and WordPress will detect and use them as needed.
As per http://nacin.com/2012/03/29/page-templates-in-subdirectories-new-in-wordpress-3-4/.