phpwordpress

Wordpress 'pre_get_posts' is ignored


I've seen others previously have issues with 'sticky' posts. That is not the case here. No matter what value I pass in for posts_per_page, when I check the resulting query via the 'Query Monitor' plugin or the database call, it appears that posts_per_page is being overridden to 5. I need to set that to 8, and enable paging for this custom event post type. Any ideas what I might be doing wrong?

Thanks!

Note: I provided my full code block, I am trying to separate future and past events, currently I am focusing on pagination and posts per page for historical events.

add_action( 'pre_get_posts', function( $query ) {
  if ( ! is_Admin() && $query->is_post_type_archive('gander_event') && $query->is_main_query()) {
      if (get_query_var('show_history') == 'yes') {
        //$query->set( 'nopaging', true);
        //$query->set( 'posts_per_page', -1 );
        $query->set( 'posts_per_page', 3);
        $query->set( 'nopaging', false);
        $query->set( 'ignore_sticky_posts', true);
        //$query->set( 'paged',  1); //get_query_var( 'page' ) ? get_query_var( 'page' ) :
        
        $query->set( 'orderby', 'meta_value');
        $query->set( 'order', 'desc');
        $query->set( 'meta_key', 'event_start_date_seconds');
        $query->set( 'meta_query', array(
                            'type' => 'NUMERIC',
                            'key' => 'event_end_date_seconds',
                            'value' => date('U'),
                            'compare' => '<'
                            ));
      } else {
        $query->set( 'nopaging', true);
        $query->set( 'posts_per_page', -1);

        $query->set( 'orderby', 'meta_value');
        $query->set( 'order', 'asc');
        $query->set( 'meta_key', 'event_start_date_seconds');
        $query->set( 'meta_query', array(
                            'type' => 'NUMERIC',
                            'key' => 'event_end_date_seconds',
                            'value' => date('U'),
                            'compare' => '>'
                            ));  
      }
  }
} );

Solution

  • It sounds like a priority issue.
    Your theme or a plugin may be using the same hook and modifying the query after you.

    add_action() has a third parameter, $priority that determines in what order functions linked to that hook will run. It defaults to ten, try setting it higher (e.g. add_action( 'pre_get_posts', function() {}, 20 );) and see if that fixes the issue.

    See the Wordpress documentation for more info:
    https://developer.wordpress.org/reference/functions/add_action/