Is there a way to define the $post var outside the loop?
Question
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();
$new_query->query('post_type=post&paged='.$paged);
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;
break;
case "Category 2":
$cat2[] = $post;
break;
case "Category 3":
$cat3[] = $post;
break;
}
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;
include('front_page_loop.php');
}
Where front_page_loop.php
is my loop code, but I just get the same post, albeit with different dates
Solution
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 ) {
setup_postdata($post);
printf( 'Post "%s" was posted %s ago<br />',
get_the_title(),
human_time_diff( strtotime( get_the_date() ) )
);
}