WordPress.org

Make WordPress Core

Opened 4 years ago

Last modified 5 weeks ago

#14310 reopened enhancement

Template hierarchy filter — at Initial Version

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

Description

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_candidates', 'author_role_template');

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

Change History (1)

scribu4 years ago

Note: See TracTickets for help on using tickets.