WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to speed up a wordpress site by condensing three wp_queries into one. I have a need to seperate categories, so I am making the call and defining 3 arrays to hold the post using a switch, like so:

 $new_query = new WP_Query();
                if ( $new_query->have_posts() ) : while ( $new_query->have_posts() ) : $new_query->the_post();              
                $category = choose_one_category(get_the_category());

                switch ($category){
                    case "Category 1":
                        $cat1[] = $post;
                    case "Category 2":
                        $cat2[] = $post;
                    case "Category 3":
                        $cat3[] = $post;

                endwhile; endif;

which leaves me with 3 arrays which with the posts nicely sorted. Now I wish to define the variable $post OUTSIDE the loop so that I can use methods like the_date() & comments_number() without having to rewrite those functions, can anyone help?

I have tried:

                    foreach ($centre as $new_post){
                        $post = $new_post;


Where front_page_loop.php is my loop code, but I just get the same post, albeit with different dates

share|improve this question
up vote 1 down vote accepted

I think setup_postdata($post) (internal) function does that. I failed to find proper documentation for it in Codex (typical), but there are examples with it here and there like in Displaying Posts Using a Custom Select Query.

This test snippet seems to work fine for example code you have in question:

foreach ( $cat1 as $post ) {

    printf( 'Post "%s" was posted %s ago<br />',
        human_time_diff( strtotime( get_the_date() ) )
share|improve this answer
Almost, all the titles are the same. The first post's title – Mild Fuzz Sep 29 '10 at 18:41
and the date. In fact, I don't think anything but content is changing!! – Mild Fuzz Sep 29 '10 at 19:35
Added test snippet to my answer, which seems to work fine. – Rarst Sep 29 '10 at 20:12
For clarity, to anyone else reading, the above seems to work only when you use the var $post. It seems the set_postdata() method converts $post, rather than defining it – Mild Fuzz Sep 29 '10 at 22:17
...if that makes sense? – Mild Fuzz Sep 29 '10 at 22:18

Your Answer


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.