Pre_get_posts + archive template / controller mismatch

I’m running into a strange issue. I have the post type ‘collection’ with the associated controller and template (ArchiveCollection.php and archive-collection.blade.php). I need to include posts from another post type on this archive page. Originally I was doing so by simply adjusting the query within the controller, but I ran into an issue where pagination wouldn’t work once I exceeded the number of pages that would be returned with the default query (see this Stack Exchange thread: https://wordpress.stackexchange.com/questions/176347/pagination-returns-404-after-page-20). So instead I’m attempting to use pre_get_posts to add in the new post type.

However this creates an issue – once I add the new post type, archive-collection.blade.php is no longer called when I view the archive, instead archive.blade.php gets used. But! The Archive.php controller is not used, ArchiveCollection.php is still being used instead. So the controller and the template don’t match, resulting in a bit of a mess.

This seems like a bug, and while I think I have a nasty workaround, ultimately I’d like to find a way to ensure the right template is used instead of defaulting back to the basic archive template.

What version of Sage are you using?

I’m currently on version 9.0.9

That version of Sage is probably still using sober/controller. There are two important things to keep in mind about that version of Sage and that package:

  1. It can only match two controllers (App and one other template-specific one) unless you enable the tree.
  2. It matches based on the WordPress template hierarchy, and it determines where it is by looking at the classes WordPress adds to body_class.

My guess is that WordPress is correctly serving the ‘archive’ template because that matches the query, but that the body_class may still be set in such a way the Controller matches ArchiveCollection. If that’s the case, you may be able to solve the problem by filtering/modifying the body_class to remove archive-collection or to add a different class you can match against, i.e. combined-archive or something.

Incidentally, this is a problem that we’ve solved in Sage 10 through the use of Composers, which are tied directly to the actual template files instead of WordPress’s template hierarchy. This article is a bit dated at this point, but by and large it still stands: https://roots.io/working-with-composers-in-sage-10/ Sage 10 doesn’t have an official release yet, but I’ve used it as-is on a number of production projects.

This topic was automatically closed after 42 days. New replies are no longer allowed.