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

(avery) #1

56 PART I • Getting Started with WordPress


restore $post to where it was in the original query — something that might be what you’re
after should you go off on your own within a loop. You can read more about wp_reset_
postdata() in the Codex at http://codex.wordpress.org/Function_
Reference/wp_reset_postdata.

Say you want a box at the bottom of the page showing the last five posts from the News
category; this can be achieved by using WP_Query, which takes the same arguments as
query_posts() (touched upon earlier):

<?php
// Arguments for WP_Query
$args = array(
'category_name' => 'news',
'showposts' => 5
);
// The new loop stored in $new_loop
$new_loop = new WP_Query( $args );
while ( $new_loop->have_posts() ) : $new_loop->the_post(); ?>

<!-- Loop output goes here -->
<?php
// Loop ends
endwhile;
// Reset the query
wp_reset_postdata();
?>

This would then output the five latest posts from the News category, which you would put in
the box mentioned in the previous paragraph.

FEATURED POSTS WITH MULTIPLE LOOPS
Another common usage for multiple loops is to display a featured post at the top of the page.
This allows the WordPress theme to break from the traditional blog layout and has become
quite popular, especially with the so-called magazine themes that mimic their print
counterparts.

To do this, you first need a loop that fetches a single post — the latest one, naturally — from
the Featured category. Then, you need a second loop that does the regular thing, listing the
latest posts from all categories. To pull this off, you need to store the first loop query inside its
own query object. Do that by calling the WP_Query object and storing it in a new query.
WP_Query is the big huge thing that makes the loop tick. Although you don’t see it in the
basic loop, you actually use it with have_posts(), for example, which in essence is $wp_
query->have_posts(); you just don’t have to write it all out all the time. WP_Query is
huge and somewhat complicated, so messing with it requires some decent coding skills or a
lot of trial and error. As any experienced PHP coder will tell you, a little of both usually does
the trick. Often, however, you’ll interact with WP_Query by using the various template and
conditional tags.
Free download pdf