16. WP_Query()


Image

Until now we’ve used the user location on the site to dictate what posts to show in The Loop. The Loop automatically detects whether a user is on the Articles category, for example, then displays only posts in that category. This is a really helpful function and it makes it easy to display content. However, there are times when you might want more freedom and control over the content.

You may want to display posts but exclude everything from a specific category or maybe you want to show only posts from the previous month. More simply, you might want to show a different number of posts than what is set in the default settings.

Our theme has a home page slider, which we have yet to code out. In this case we need to display up to five posts from a specific category. This chapter will show you how to use WP_Query(), a powerful class that lets you set the specific categories and number of posts to display.

What you’re about to learn

• Solutions for filtering the basic loop

• An in-depth look at WP_Query()

• Alternatives and best practices for querying specific data

• Ideas for improving or building on a theme with WP_Query()

Getting Started with Custom Queries

There are many reasons why you might want to create custom queries to filter a request for posts or other content. WP_Query() lets you tap right into the WordPress API and filter, change, or modify The Loop however you want. But before we jump into WP_Query(), let’s look at a quick and easy alternative.

query_posts()

The function below is an outdated way to alter The Loop:

<?php query_posts() ?>

There are several drawbacks to using query_posts(), but knowing how it works will enable you to reverse engineer other developers’ code. You may see query_posts() in action a lot because it’s a simple way to alter The Loop. For example, let’s say you want to display all the posts from your Tutorials category from the year 2011.

To request posts from a specific category and year we need to alter The Loop. This function call goes directly above the first line of The Loop and changes the parameters of The Loop by passing those values through query_posts():

<?php query_posts( 'cat=8&year=2011' ); ?>

There are many parameters you can pass to this function—everything from author ID to publication date to specific post IDs. You can even decide how you want to order the posts (by date, alphabetically, or otherwise).

The query_posts() function accepted ‘cat=8&year=2011’ as parameters. This is technically a single PHP parameter because it’s in one “set.” However, we’re separating specific filtering parameters with the “&” so we can pass multiple values in one parameter. When this is placed above The Loop, The Loop definition is redefined and no longer dependent on the user’s location on the site. This requires The Loop to return posts that are posted in category 8 and published in 2011.

One drawback to using query_posts() is that it can potentially redefine all the loops on the template page. In the index.php template file we’ll require a loop for the slider and an additional loop for the recent content. We’ll need to reset the query parameters after The Loop by inserting the code below, immediately after the end of The Loop:

<?php wp_reset_query(); ?>

For more information on query_posts() and wp_reset_query()visit the codex at http://wdgwp.com/query_posts and here http://wdgwp.com/wp_reset_query.


Note

We’ll need the category ID in several places in this chapter. To quickly find category, post, page, tag, or even site IDs, simply roll over the link in the admin and the ID will appear in the information bar at the bottom of the browser (Figure 16.1). There you’ll see “tag_ID=8” in the URL, which means that the Tutorials category ID is 8. Alternatively, you can click the category link and see the ID in the URL bar at the top.

Image

Figure 16.1. Finding the Category ID in the browser information bar.


A Basic WP_Query()

A better solution to the problem is to use the WP_Query() class. It requires a little more work but there are several advantages, many of which we’ll cover shortly. The great thing about WP_Query() is that it can be used to create simple queries to extremely complex queries. You can read more about it and see the full list of parameters at http://wdgwp.com/WP_Query.

Let’s use WP_Query() to replicate the same results as above. The process is pretty much the same. Above the loop we’ll define a series of parameters that will change the output of the loop:

<?php
  // The Query
  $the_query = new WP_Query( 'cat=8&year=2011' );

  // The Loop
  if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) :
        $the_query->the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

<?php
  endwhile; endif;

  // Reset Post Data
  wp_reset_postdata();
?>

The first thing we need to do is define a new instance of the WP_Query class, like so: $the_query = new WP_Query( $args ). Once we define a new instance of the class we can pass it the parameters and call it in our loop later. For more info on PHP classes, go to http://wdgwp.com/php_classes.

Our loop gets modified a bit but the basic idea is still there. Inside the loop we continue to use our HTML mixed with Template Tags to create a list of post titles and links.

At the end of the code we close the while loop and reset the global $post data with the wp_reset_postdata() function. You can read more about that at http://wdgwp.com/wp_reset_postdata.

Once the code runs, it returns a list of posts, their titles, and links wrapped in <li></li> tags that reside only in the Tutorials category and were published in 2011. It was a little more work to create our loop in this fashion, but in the end, it’s a better practice and makes for better, more scalable themes.

Slider

We’ll populate our home page slider with HTML from a WP_Query() loop. Early on we decided to use a specific category called “Slider” to hold all our slider posts. (Remember that this isn’t the best solution for this task, but defining custom post types is out of the scope of this book.) In the admin I created a new category with the ID of “9.” The other element to the slider is that we want to feature a maximum of five posts at a time. So, in our WP_Query() parameters we need to define the category ID 9 and limit the number of results to five. Above, we passed our parameters together as a string. This time we’ll create an array and then pass it to the WP_Query() class. This makes it easier to conceptualize our parameters and keeps things better organized.

Open the index.php template file and in the slider HTML (which is defined for you) place the following PHP code:

<?php
  // The Query
  $j2theme_slider_param = array (
    'cat' => '9',
    'posts_count' => '5',
    );

  $the_query = new WP_Query( $j2theme_slider_param );

  // The Loop
  if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) :
        $the_query->the_post();
?>

    <a href="<?php $j2theme_slider_url = get_post_custom_values('url'),
        echo $j2theme_slider_url[0];?>" title="<?php the_title(); ?>"><?php
        the_post_thumbnail('slider'), ?></a>
  <?php
  endwhile; endif;

  // Reset Post Data
    wp_reset_postdata();
?>

Let’s go through this step by step. The first thing to do is define the array, $j2theme_slider_ param, which will hold our parameters’ definitions. Remember, it’s good practice to preface your variables with a custom prefix. The format of the array declaration is something you’ll have to get used to, as it’s just basic PHP format. You can learn more about defining PHP arrays at http://wdgwp.com/php_arrays. In the array we’re assigning ‘9’ to ‘cat’ and ‘5’ to ‘posts_count’. These parameter names are set by WordPress. For a full list of what you can define in WP_Query() go to http://wdgwp.com/WP_Query_params.

With the array complete the next step is to pass it to the new instance of WP_Query(). Immediately following $the_query declaration is our modified loop. Inside The Loop the structure of the HTML is based on the requirements for the jQuery-based Nivo Slider, which asks for wrapping the featured image in an <a> tag. Notice the use of the get_post_custom_ values() function, which we use to pull the URL custom value set by the user admin. (Refer back to Chapter 15, “Custom Fields.”)

The last steps are to close the while loop and reset the post data. This freshly defined loop returns a maximum of five posts from the Slider category, displays its featured image (“slider” size), title, and “url” custom field. Once this HTML is output (see below) the Nivo Slider code does the rest of the work, configuring the jQuery and functionality of the slider:

<a href="http://jesserfriedman.com" title="About Jesse Friedman"><img
        width="530" height="215" src="http://localhost/j2-theme/wp-content/
        uploads/2012/05/jesse-530x215.png" class="attachment-slider wp-post-
        image" alt="Image of Jesse Friedman" title="About Jesse Friedman" />

<a href="http://worldclassdesigner.com" title="About Jeff Golenski"><img
        width="530" height="215" src="http://localhost/j2-theme/wp-content/
        uploads/2012/05/jeff-530x215.png" class="attachment-slider wp-post-
        image" alt="Image of Jeff Golenski" title="About Jeff Golenski" />

Now that the slider is properly defined, the user admin can add as many posts to the Slider category as she pleases. The user admin can define slides as “on” or “off” by setting them to draft or published, and reorder them by changing the publication dates on the posts.

Using Custom Queries

We just built our home page slider by creating an alternative loop. This was a great example of the WP_Query() because it covered all the basics and was rather simple to do. In the future, you can use WP_Query() to do a variety of things and add really complex functionality to your site. Let’s take a look at some fun ways to use what we just learned. These examples show only the changes made to the parameters array. The rest of the loop would change based on the necessary HTML structure.

Featured Author

Imagine you have a large blog or article-based website with dozens of staff contributors and guest writers. One thing you don’t want to do is lose access to the founder and head writer. Maybe they only contribute once a week or once a month. It’d be easy for their articles to get lost in the mix.

We can use WP_Query() to define an author ID and pull posts from only the specific head writer. Or if you have multiple featured authors, you can pass several author IDs. This is a great solution to featured content on the site’s home page. Place your new loop in the home template file and you’ll be showcasing your head authors above everything else:

$parameters = array (
  'author' => '1',
  'posts_count' => '3',
);

The above code displays the three most recent posts from the author with ID 1. You can also call multiple authors, as shown in the following example:

$parameters = array (
  'author' => '1,5,8',
  'posts_count' => '3'
);

In this case all you have to do is place commas between the IDs and the most recent posts from these authors will display. It’s important to note that you’re not getting the three most recent posts from each author. Instead the query finds the three most recent posts from any of the authors. So, if author 5 wrote the last three posts, only hers would be displayed.

Company Blog

Another common example would be excluding a specific category from the template page. Let’s say your company has a blog with several categories, one of which is specifically geared to investors. To everyone else these articles may be irrelevant or even boring. You could use the cat parameter to list only the IDs you want to show, but that’s a lot of work. Instead you can just state which category you want to exclude:

$parameters = array (
  'cat' => '-7'
);

We still use the “cat” parameter this time, but notice the “-” symbol before the number 7. This tells the query that we need to “minus” or exclude category 7. You can use the minus symbol in front of many values in WP_Query().

Locations Custom Post Types

We haven’t built custom post types but in the future you might well be doing a lot of them. You might have a site utilizing custom post types to create locations. In this case you can use WP_Query() to display all the locations and sort them alphabetically:

$parameters = array (
  'post_type' => 'locations',
  'orderby' => 'title',
  'order' => 'ASC',
);

The ‘post_type’ parameter can accept inherent post types like “post” or “page.” It can also accept developer-defined custom post types like “locations.” Next, define the “orderby” parameter, which has several choices like title, ID, date, comment count, and more. The last parameter is “Order,” which is either “ASC” (a,b,c or 1,2,3) or “DESC” (c,b,a or 3,2,1).

What’s Next

We just covered WP_Query() pretty extensively, but there are many more ways to use this class. The best way to figure out what can be done is to imagine using or filtering content and reverse engineering it. Take a close look at http://wdgwp.com/WP_Query_params and you’ll get a good idea of how far you can take this powerful class. In the next chapter, we’ll create basic functions, define shortcodes, and take some time to organize our functions.php file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.67.85