4

I'm trying to set the number of posts_per_page dynamically using my own variable. This code works fine:

query_posts( $query_string  . "&posts_per_page=" . $myvar )
// then display the loop using get_template_part( 'loop' );

That works fine, but I would like to know how to do it using $wp_query instead of query_posts. However, this does not work:

$wp_query->set('posts_per_page', $myvar)
// then display the loop using get_template_part( 'loop' );

That has no effect on the number of posts displayed. Am I using the set method incorrectly, or is there something I'm missing?

4 Answers 4

14

query_posts will do the query again (destroy current wp_query and create a new one and then doing the query with the parameters you pass to it)

To get the same behaviour after setting the new parameter with set_var you need to query the database again using something like this

 $wp_query->set('posts_per_page', 1);
 $wp_query->query($wp_query->query_vars);
2

when you call query_posts with a modified query in your template, you're actually running another query and discarding the original. trying to set a query var in your template doesn't work because the original query has already happened. to use $wp_query->set() you have to hook in before the database is queried, for example on pre_get_posts.

1

Why do you need to use $wp_query->set() at all?

Can't you just use:

<?php
$my_custom_query_args = array(
    'posts_per_page' => $myvar
);
$my_custom_query = new WP_Query( $my_custom_query_args );
?>
1
  • 1
    Aren't you destroying all other query arguments that way? The ->set() method should keep the rest of the arguments the same, just change post_per_page. Or am I misreading this? Commented Sep 13, 2021 at 16:36
-1

You may use

$wp_query->query_vars['posts_per_page'] = 25
1
  • Hi! Can you please be a bit more verbose with your answers and explain the why this answer helps-part as well? Else answers get automatically flagged as low quality by the community bot. Thanks. Hint: You will have to at least wrap your call in a callback function attached to a filter :)
    – kaiser
    Commented Jun 27, 2016 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.