Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 3 • The Loop 57


Recall the query_posts() template tag. The usage description says that it is intended to
modify the main loop only, so you won’t be using that for your new loop. Instead, pass the
same variables to WP_Query. Here is the code:


<?php
// Setting a temporary value to avoid errors
$do_not_duplicate = null;
// Loop arguments
$args = array(
'category_name' => 'featured',
'showposts' => 1
);
// Our featured query and loop
$featured_query = new WP_Query( $args );
while ( $featured_query->have_posts() ) : $featured_query->the_post();
// Save the post ID to $do_not_duplicate
$do_not_duplicate = $post->ID;
?>



<?php
// Featured loop ends
endwhile;
// Resetting
wp_reset_postdata();
?>



<?php
// Loop arguments
$args = array(
'showposts' => 9
);
// Our second loop
$second_query = new WP_Query( $args );
while ( $second_query->have_posts() ) : $second_query->the_post();
// Let's not output the featured post
if ( $post->ID == $do_not_duplicate ) continue; update_post_caches( $posts );
?>



<?php
// Second loop ends
endwhile;
?>


Take a closer look at this code. The first thing happening is that $do_not_duplicate gets
set to null, to avoid any errors should there be no posts in the featured loop. Then there’s the
arguments that you use in WPQuery for controlling what the loop should contain. WP
Query is stored in $featured_query, which you then use in the actual while loop.
You’ve seen this before. Finally, you save the result of the loop to $do_not_duplicate,
which is the one post ID. Note that although it is easy enough to output two or more featured
posts by changing the showposts argument for WP_Query, you’d have to store these post
IDs in an array for $do_not_duplicate to work.

Free download pdf