Make WordPress Core

Opened 5 years ago

Last modified 4 weeks ago

#14310 accepted enhancement

Make template hierarchy filterable — at Version 5

Reported by: scribu Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version:
Component: Themes Keywords: has-patch 4.5-early
Focuses: template Cc:

Description (last modified by scribu)

Currently, we have filters for each template type: home_template, author_template etc.

The trouble is that these filters are applied on the final template path, after the template hierarchy has been traversed.

It would be useful if there was another filter applied to the actual template hierarchy array, before it was sent to locate_template().


Take the author template hierarchy:

author-{nicename}.php > author-{id}.php > author.php

Say I want to add author-{role}.php before author.php.

Sure, I could use the 'author_template' filter:

function author_role_template( $old_template ) {
  // get current author's role

  $new_template = locate_template( array( "author-$role.php" ) );

  if( $new_template && 'author.php' == $old_template )
    return $new_template;

  return $old_template;
add_filter('author_template', 'author_role_template');

With an 'author_template_candidates' hook, I could manipulate the actual hierarchy:

function author_role_template( $templates ) {
  // get current author's role

  $new_template = array( "author-$role.php" );

  $templates = array_merge( 
    array_slice( $templates, 0, -1 ), // before
    $new_template,                    // inserted
    array_slice( $templates, -1 )     // after

  return $templates;
add_filter('author_template_hierarchy', 'author_role_template');

This would allow me to remove author-{id}.php if I wanted, etc.

Change History (8)

#1 @scribu
5 years ago

template_candidates.diff makes all get_*_template() functions call get_query_template(), which consistently applies the appropriate filters.

#3 @scribu
5 years ago

  • Summary changed from Template hierarchy filter to Make template hierarchy filterable

#4 @F J Kaiser
5 years ago

  • Cc 24-7@… added

5 years ago

Name the filter *_template_hierarchy

#5 @scribu
5 years ago

  • Description modified (diff)

template_hierarchy.diff just renames the filter *_template_hierarchy, which seems more appropriate.

5 years ago


Note: See TracTickets for help on using tickets.