WordPress: Run a query loop without interfering with the global $post
This example runs a query with some (prearranged) arguments to get related post thumbnails. More importantly, it’s an example of how to run a WP_Query in WordPress without affecting the global data. Notice the get_the_ID() call which checks the current scope’s post id…
|
1 2 3 4 5 6 7 8 9 10 11 12 |
$wpq = new WP_Query($args); $thumbs = array(); while ($wpq->have_posts()) : $post = $wpq->next_post(); // Special active class for this pages thumb $attr = array(); if ( $post->ID == get_the_ID() ) $attr['class'] = 'active'; $thumbs[] = get_the_post_thumbnail($post->ID, 'photo-thumb', $attr); endwhile; |
Before I had the code below which was overwriting the global $post (via ->the_post()) which caused all the thumbs to be labelled as “active”.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
$wpq = new WP_Query($args); $thumbs = array(); while ($wpq->have_posts()) : $wpq->the_post(); // Special active class for this pages thumb $attr = array(); if ( $wpq->post->ID == get_the_ID() ) $attr['class'] = 'active'; $thumbs[] = get_the_post_thumbnail(null, 'photo-thumb', $attr); endwhile; |


