[wp-trac] [WordPress Trac] #42764: Template Hierarchy does not work with multiple post types

WordPress Trac noreply at wordpress.org
Fri Dec 1 03:29:19 UTC 2017


#42764: Template Hierarchy does not work with multiple post types
--------------------------+------------------------------
 Reporter:  nbdamian      |       Owner:
     Type:  defect (bug)  |      Status:  new
 Priority:  normal        |   Milestone:  Awaiting Review
Component:  Themes        |     Version:  4.9.1
 Severity:  normal        |  Resolution:
 Keywords:                |     Focuses:  template
--------------------------+------------------------------

Comment (by nbdamian):

 Replying to [ticket:42764 nbdamian]:
 > Inside the "pre_get_posts" action, If you set the post_type argument to
 multiple, I.E:
 > {{{#!php
 > <?php
 > add_action( 'pre_get_posts', function($query) {
 >   if (!is_admin() && $query->is_main_query() && !$query->is_search() &&
 is_post_type_archive('event')):
 >     $query->set('post_type', array( 'event', 'product' ) );
 >   endif;
 > }
 > }}}
 >
 > This will force the templating hierarchy to use "archive.php" instead of
 either "archive-event.php" or "archive-product.php"
 >
 > Currently, I am working around this issue using:
 > {{{#!php
 > <?php
 > add_filter( "archive_template_hierarchy", function($templates) {
 >       $post_types = get_query_var('post_type');
 >       if (count($post_types) > 1 && count($templates) == 1):
 >               foreach ($post_types AS $post_type):
 >                       array_unshift($templates,
 "archive-".$post_type.".php");
 >               endforeach;
 >       endif;
 >       return $templates;
 > }, 10, 1 );
 > }}}
 >
 > Unsure if this is a bug, or intended. Either way, it would be useful to
 support this.



 This could be resolved by changing template.php line 114 from
 {{{#!php
 <?php
 if ( count( $post_types ) == 1 ) {
         $post_type = reset( $post_types );
         $templates[] = "archive-{$post_type}.php";
 }
 }}}
 To:

 {{{#!php
 <?php
 if ( count( $post_types ) == 1 ) {
         $post_type = reset( $post_types );
         $templates[] = "archive-{$post_type}.php";
 } elseif ( count( $post_types ) > 1 ) {
         foreach($post_types AS $post_type) {
                 $templates[] = "archive-{$post_type}.php";
         }
 }
 }}}

--
Ticket URL: <https://core.trac.wordpress.org/ticket/42764#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list