Using pre_get_posts not working

I’m trying to alter the order of posts displayed on a custom taxonomy archive page. I have created a custom taxonomy archive template, which is working fine. I am using the standard method of altering the query on this page, with the following code:

 function stage_tax_query_modifications( $query ) {
  if( $query->is_main_query() && $query->is_tax('custom-tax') ) {

    $query->set( 'orderby', 'date' );
    $query->set( 'order', 'DESC' );

  } 
}
add_action('pre_get_posts', 'stage_tax_query_modifications');

But nothing I enter here (and I have tried a few different valid values for ‘orderby’ and ‘order’) alters the posts at all. I am wondering if it is something to do with the theme wrapper?

Any help appreciated!

Where have you defined the function and action?

1 Like

I have put it in extra.php

It’s not the wrapper. You can test in one of the twenty* themes, but it looks like these changes in 4.0 are the issue: https://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/

Are you seeing any errors/warnings? I assume you have WP_DEBUG on.

If you’re using Sage 8.*, then it also looks like you’re missing the Namespace when passing the function name.

2 Likes

No - I tested with 2015 theme and my function works perfectly, so must be something about Sage…

Ah thank you - how do I pass the Namespace?

No worries, got it…thank you!

Hey @josephclawrence – could you elaborate how you got things running? Am struggling myself to use a similar function. Thanks!

It was a while ago now, but I think I followed the Namespace guidelines outlined at this link: https://roots.io/upping-php-requirements-in-your-wordpress-themes-and-plugins/

Allright, just found that post too, will try my best!

Thanks guys for the help. For future readers not wanting to dig through the doc, here’s the working code :

add_action('pre_get_posts', __NAMESPACE__ . '\\stage_tax_query_modifications');
1 Like