Loading template files from a subfolder in my theme?

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.

Read More

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);

Related posts

Leave a Reply

3 comments