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?


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);
| improve this answer | |

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.

| improve this answer | |

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

Can't you just use:

$my_custom_query_args = array(
    'posts_per_page' => $myvar
$my_custom_query = new WP_Query( $my_custom_query_args );
| improve this answer | |

You may use

$wp_query->query_vars['posts_per_page'] = 25
| improve this answer | |
  • 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 Jun 27 '16 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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