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

(avery) #1

58 PART I • Getting Started with WordPress


The actual output of the loop’s content isn’t covered in this example. It can be anything,
perhaps a featured image, a nice headline, and the post excerpt. Anything you’d normally
output within the loop will work. Next, you close the loop with endwhile and reset the post
data with wp_reset_postdata().

The second loop, which contains the rest of the posts that are meant to go after the featured
one, is built in a similar fashion. Do note that WP_Query is stored in $second_query here.
The one thing that truly differs is the check to see whether a post ID is the same as the one
used in the earlier featured loop. If it is, the loop will just skip it.

THREE’S A CHARM, BUT FOUR LOOPS ARE WAY COOLER
Using the knowledge you’ve gained thus far, in this section you’ll put the multiple loop concept
to the test. In this example, you’ll have three featured posts in one loop, and then you’ll
imagine three columns underneath consisting of the latest posts from one category each. The
idea is to mimic the front page of a nonbloggish site. In terms of template files, this would
ideally be in the home.php template, which means that it would be loaded only when on the
front page. It could also be a Page template belonging to a page set as the front page for the site.

This example will use the same principle as the previous one but with four queries. The top
one consists of three featured posts, and below that you have three queries sorted after
category. Start with the featured posts:

<div id="featured">

<?php
// Setting a temporary value to avoid errors
$do_not_duplicate = null;
// Loop arguments
$args = array(
'category_name' => 'featured',
'showposts' => 3
);
// 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;
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1>
<a href="<?php the_permalink(); ?>"
title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h1>
<?php the_excerpt(); ?>
</div>
Free download pdf