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

(avery) #1

CHAPTER 3 • The Loop 45


So what is happening? Well, get_template_part( 'content', 'archive' ) looks
for content-archive.php first, where you’ll put your custom loop, hence making content.php
clean and slim. Should content-archive.php not be present, content.php will be used instead,
and this is where you’d put a general “if all else fails” loop output. You’ll put this to good use
with child themes in Chapter 5, “The Child Theme Concept.” For now, you can be happy
knowing that this is a great way to separate the loop code, which can be quite extensive,
from the various template files.


There’s no law that says you need to use loop.php or even that kind of separation of
the loop. You could include just about anything with get_template_part(),
and you might prefer to have the obvious parts of the loop within the actual
template file, including specific parts depending on what post format a post can
have, for example.

A FEW WORDS ABOUT WP_QUERY


WP_Query is the heart of the loop, even though you don’t see it spelled out in the most basic
code. It is really a class that handles all the loop magic, and you’ll find it in wp-includes/query.
php if you want to dig deep within the WordPress core files. Refer to the Codex page at
http://codex.wordpress.org/Function_Reference/WP_Query for an
explanation of all the properties and methods that go with WP_Query.


The basic loop uses WP_Query, or rather it uses the default $wp_query object. This means
that when you use necessities such as have_posts() and the_post(), you’ll in fact use
$wp_query->have_posts() and $wp_query->thepost(). In other words, have
posts() and its friends take it for granted that you want to be using $wp_query. Whenever
you go outside $wp_query by creating your own queries, as you’ll do in the “Multiple Loops”
section as well as in examples and adaptations further in the book, you’ll have to create an
object for it, like this:


<?php $brand_new_query = new WP_Query(); ?>


Here, you’re loading everything into $brand_new_query instead of the default
$wp_query, which means that you can do stuff outside of the main loop.


Most parts of WordPress connect to the WP_Query class, including templates and condi-
tional tags. You can tap into and alter things within the WP_Query class, but you should
refrain from it if there is an available solution already. As you master WordPress, there may
come a time when you want to do things that are truly out of the box, but that’s a whole
other matter.

Free download pdf