“pre_get_posts” firing on every query

How can I change arguments for the main query only, and not affect other queries?

add_filter('pre_get_posts', 'custom_post_count');
function custom_post_count($query){
  $query->set('posts_per_page', 5);
  return $query;
};

Because this action is called inside the get_posts method of WP_Query, this code will alter the posts_per_page argument for all loops, not just the main, so passing this argument to WP_Query is useless…

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Basically what you are looking for is the global $wp_the_query variable which is set to the value of the main query. It may not be a perfect fit for 100% of cases but will probably work fine in 99% of cases:

add_action( 'pre_get_posts', 'custom_post_count' );
function custom_post_count( $query ){
  global $wp_the_query;
  if ( $wp_the_query === $query ) {
    $query->set( 'posts_per_page', 5 );
  }
  return $query;
};

Method 2

Firstly, ‘pre_get_posts’ is an action and not a filter. That’s the main problem to start. Secondly, you need to set conditionals for the context.

add_action('wp', 'custom_post_count');
function custom_post_count($query){
    if($query->is_home || $query->is_front_page){
        $query->set('posts_per_page', 5);
    }
    return $query;
};

The previous example is if you want to use this once in your functions.php without touching your template files. As far as affecting every query, if you don’t create a new query, every loop with inherit the pre_get_posts $query. That’s why I use query_posts() to create a new query in the following example.

Custom Loops

This is how I do custom loops:

$args = array(
    'posts_per_page' => 5
);
query_posts($args);

if(have_posts()): while(have_posts()): the_post();


endwhile; else:

endif;

wp_reset_query();

Just place query_posts() above the loop and wp_reset_query() at the end of the loop.

Hope this helps you out. 🙂


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x