4

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?

2 Answers 2

7

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.

1
  • 1
    Thank you, I never knew that it would search subdirectories as well as the theme root directory!
    – PeterB
    Commented Apr 22, 2014 at 20:55
3

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';
    }
2
  • 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
    Commented Apr 22, 2014 at 14:47
  • Thanks @Rarst, I feel less bad about not knowing now :)
    – PeterB
    Commented Apr 22, 2014 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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