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


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() ) )
  • 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 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.