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

(avery) #1

54 PART I • Getting Started with WordPress


Let’s start with looking at how to implement pre_get_posts, which can be done in a
number ways, depending on whether you’re working with a theme or a plugin. In a theme’s
functions.php file, you can create a function with your query changes, such as excluding the
category with ID 13, for example. This function will the be added to the pre_get_posts
action. Hooks are covered more extensively in Chapter 7, “Making the Most of WordPress
Plugins,” so let’s just keep it short and simple for now:

function smashingtheme_exclude_category( $query ) {
$query->set( 'cat', '-13' );
}
add_action( 'pre_get_posts', 'smashingtheme_exclude_category' );

This hides the posts from the category with ID 13 on your site because pre_get_posts will
be called for before the actual query. However, this is also true for the admin interface, so
your Edit Posts listing in wp-admin would also exclude the category with ID 13. To remedy
this, you could use the is_main_query() conditional tag to limit to just the site’s main
query, or you could just not make this function trigger when you’re in the admin area:

function smashingtheme_exclude_category( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
$query->set( 'cat', '-13' );
}
}
add_action( 'pre_get_posts', 'smashingtheme_exclude_category' );

This will limit the function to when it’s not the admin area (the is_admin() conditional tag
is false) and when it is the main query.

There are a lot of things you can do with pre_get_posts, such as change the number of
posts on archive listings but not the front page or include/exclude certain content from search
results, for example.

When digging into themes and tutorials, you’ll often come across query_posts().
This is a function for altering the main query. It’s not recommended to use
query_posts() anymore. If you need to alter the main query, use
pre_get_posts() and is_main_query() instead.

ALTERNATIVES TO THE LOOP


You may be tempted to create multiple loops or advanced loop queries in your theme’s
template files when you’ve figured out how those work. Whereas that may be the solution to
what you want to do in some cases, you should consider alternative methods as well. Doing a
lot of funky stuff with the loop is sometimes completely unnecessary. Here’s why.

First, ask yourself if it really is another loop you need. Often there are template tags that can
do what you need, and that is almost always a better solution. Custom loop magic should be
saved for actions that truly deserve and need it. At other times, a conditional tag might be the
solution to the problem, which usually is a better approach than another loop.
Free download pdf