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

(avery) #1

CHAPTER 3 • The Loop 55


Second, are there any plugins that can do the work for you? The WordPress community is full
of brilliant solutions to common problems, and although it may be a lot cleaner to sort these
things from within your own theme, a plugin may enhance the functionality and be easier for
you to manage. A lot of the plugins that work with post listings are in fact doing stuff with the
loop that you could do yourself, from within your theme. Normally I would recommend the
latter solution, but what if you’re not the one responsible for maintaining the theme in the
long run, as is common when doing theme design work and then leaving it to the clients to
nurture? If your clients are reluctant to pay more for customizations, or if the clients think
that their in-house HTML skills are enough, then you’re probably better off finding a plugin
solution than one that will break when they do something with their template files. Granted,
plugins come with their own issues, such as suddenly not being developed anymore or relying
on WordPress functionality that isn’t favored, but still, it is something to consider as an
alternative to more loops.


Chapter 8, “Plugins or functions.php?,” dives deeper into the question of when to rely
on plugins to replace built-in functionality.

Finally, there is the possible strain on the server and database. Doing loop after loop means a
lot of PHP and SQL queries, and that will slow down the site. Simple is not always best, but
keeping things as simple as possible while managing to get the required result is always a good
idea. Both web hosts and WordPress have come a long way since the early days, but that
doesn’t mean that you should make things more clunky or complicated than they need to be.


My point is this: Always question the need for that extra loop. It may save you some head-
aches in the future.


MULTIPLE LOOPS


Sometimes you do want several loops on a page. Perhaps you have a category for your
extremely important posts and want to run those by themselves on the front page, or maybe
you just want the latest posts in the sidebar. Either way, whenever you need to fetch posts a
second time, you’ll want another loop. This is often essential when you want to break from the
traditional blog mold, so you may as well master it.


Start with the most basic multiple loop solution, which is to just get another loop on the page.
This is done with rewind_posts(), which just resets the loop’s counter and lets you run it
again:


<?php
rewind_posts();
while ( have_posts() ) : the_post();
?>



Naturally, this would just output the exact same thing as your first loop, which would neither
look good nor be particularly useful, so to actually do something with rewind_posts(),
you need to change something. You could also use wp_reset_postdata(), which will

Free download pdf