Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

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

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.

share|improve this answer
add comment

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 );
?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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