WordPress.org

Make WordPress Core

Opened 5 years ago

Last modified 9 months ago

#14310 reopened 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 dev-feedback
Focuses: 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().

Example

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)

@scribu5 years ago

comment:1 @scribu5 years ago

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

comment:3 @scribu5 years ago

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

comment:4 @F J Kaiser5 years ago

  • Cc 24-7@… added

@scribu5 years ago

Name the filter *_template_hierarchy

comment:5 @scribu5 years ago

  • Description modified (diff)

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

@scribu5 years ago

refresh

Note: See TracTickets for help on using tickets.