Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have to confess I'm struggling to see how the Wordpress Twenty Fourteen theme picks up templates put in the theme's page-templates folder. Previously I'd create new templates named page-<slug>.php in the theme's root folder, but not now.

I've searched the code for mentions of page-templates and not found any where files are included; searched the WP source code too and found none.

Can you explain how they're detected and picked up please?

share|improve this question

2 Answers 2

up vote 6 down vote accepted

The actual query for a Theme's page templates happens in wp_get_theme()->get_page_templates() (source), which in turn calls get_files() (source).

The magic happens here:

$files = (array) $this->get_files( 'php', 1 );

The args for get_files() are:

function get_files( $type = null, $depth = 0, $search_parent = false ) {}

So, when WordPress searches the Theme for PHP files, it passes a $depth argument of 1, which means that it searches in subdirectories of the Theme root directory.

share|improve this answer
1  
Thank you, I never knew that it would search subdirectories as well as the theme root directory! –  PeterB Apr 22 at 20:55

The important part in any page-slug.php template or a template used as a page template is the header section that identifies the page as a page template. Example of contributors.php:

/**
 * Template Name: Contributor Page
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */

The template name identifies this as a page template with name 'Contributors Page'. Page templates don't need to be registered or called in any way to be usable in the theme. They are automatically included, no matter where they are in the theme. Page templates don't have to be in the root folder to be "picked up".

In the twentyfourteen however, these templates are given a body class, for that you need to call the complete path to the template.

if ( ( ! is_active_sidebar( 'sidebar-2' ) )
        || is_page_template( 'page-templates/full-width.php' )
        || is_page_template( 'page-templates/contributors.php' )
        || is_attachment() ) {
        $classes[] = 'full-width';
    }
share|improve this answer
4  
Worth noting that discovery of page templates in subfolders is relatively recent (WP 3.4) and since relatively few themes use it — not well known feature. –  Rarst Apr 22 at 14:47
    
Thanks @Rarst, I feel less bad about not knowing now :) –  PeterB Apr 22 at 20:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.