This weeks video blog covers how to use the WP Query class in WordPress to create a custom loop that can display posts from a Custom Post Type. We will be sharing why using WP_Query is not only a more efficient but safer way to query the WordPress database.
We will be covering how to correctly set up your loop, pass in arguments, how to display posts by post type and then finally how to display posts by taxonomy.
There is a whole range of useful information shared in this video blog that could prove extremely useful to a WordPress novice.
What is WP_Query
So firstly what is WP_Query? The WP Query class enables developers to perform in-depth database queries in a safe, easy to use way.
So why is it safer?
To start interacting with WP_Query, all developers need to do is to supply simple parameters that query the object. WP Query looks after everything else including the SQL commands and ensuring proper data types are being used.
As we previously mentioned WP Query is much simpler to use than using query_posts() or writing pure SQL commands. As WordPress Developers all we need to do is enter our parameters inside an array and everything else is looked after for us. By using WP Query we are removing the need use pure SQL to obtain information.
So when would you want to use WP_Query?
The most common use of WP_Query is to run a loop. WP_Query provides a whole host of useful functions for common tasks within the loop. For example we can use the the method have_posts() to check if there are any posts to show, and if there are we can run a while loop using the method have_posts() as the condition. This allows developers to iterate through the relevant posts. To then gain access to the post information we need to make sure we call the WP_Query method the_post() inside the while statement, this will give us access to the posts title, content, featured image and other custom values.
Thats enough theory for the time being, lets head over to Dreamweaver and put WP_Query to action.
Our main aim for this tutorial is to display a range of different posts from our pre set up custom post type books. However before we jump to far ahead of ourselves, lets first create the basic fundamentals of a WP Query Loop.
The first thing we need to do is to initiate the WP_Query Class. Lets go a head and create a $wp_query variable that will contain our WP_Query object.
$wp_query = new WP_Query($args);
We can then either pass arguments directly into the parenthesis or set up an separate variable to contain all arguments. Above our WP_Query object we will create a new variable named $args that will contain an array of parameter. We will use this array later on to determine exactly what parameters we would like our loop to run.
$args = array( ); $wp_query = new WP_Query($args);
Before we display any posts onto the page, we will first want to set up a conditional statement to check that the query has returned any posts. To do this we will use the method have_posts() as a conditional for our if statement.
Its important to remember that as we are working with Object Orientated PHP, we cant call the method without specifying the object before hand followed by an arrow.
After we have checked that the WP_Query is returning posts, we now need to set up our while loop to iterate over the posts and display the post information. We do this by again use the have_posts() method as the parameter.
In order to access the post data we need to ensure that we call the method the_post() inside each iteration. the_post() sets up all of the internal variables within $wp_query along with the global $post variable.
$args = array( ); $wp_query = new WP_Query($args); /* Check Any Posts Exist */ if($wp_query->have_posts()): /* Loop through posts */ while($wp_query->have_posts()): /* Set up internal variables, and the global $post variable */ $wp_query->the_post(); endwhile; endif;
We now have access to the post data so we can go ahead and use familiar WordPress functions like the_title(), the_content() and the_post_thumbnail().
One last thing important thing to remember is that when use method the_posts() we need to ensure that once our loop is complete we use the built in WordPress function wp_reset_postdata(); The reason we call this function is to restore the global $post variable of the main loop.
$args = array( ); $wp_query = new WP_Query($args); /* Check Any Posts Exist */ if($wp_query->have_posts()): /* Loop through posts */ while($wp_query->have_posts()): /* Set up internal variables, and the global $post variable */ $wp_query->the_post(); echo '<h1>' . get_the_title() . '</h1>'; the_content(); the_post_thumbnail(); endwhile; wp_reset_postdata(); endif;
If we go ahead and run this loop now, you shouldn’t be able to see any change on the page, this is because we are yet to pass argument in. There are a whole host of arguments that can be passed through the query, and running over all of the is far beyond the scope of this tutorial, however you will be able to find full documentation on WP_Query on the WordPress Codex. A link will be provided within the supporting blog post.
Using WP_Query to display posts based on Category ID
If you head back over to your text editor, we will go ahead and perform a simple query on a post category. We can do this by passing in the following parameter ‘cat’ => 1 If we save this code and have a look at the results you can see our “Hello World” post is displayed.
Now we have tested our loop lets go ahead and add further arguments. Our aim is two pull out two posts from our custom post type “Books”. Let go ahead and add the relevant arguments.
Using WP_Query to Display Posts by Custom Post Type
We will add the arguments “posts_per_page” and “post_type”. “posts_per_page” refers to the amount of posts that the loop will display, while “post_type” refers to the name of the post type we want to return posts from. If we save the code and have a look in our browser you should be able to see our two posts returned.
$args = array( "posts_per_page" => 2, "post_type" => "books", );
As you can see the books “Harry Potter” and “Misery” are returned, just for the record both books are personal favourites of mine. Lets continue to customise our results by adding two further parameters, “order” and “order_by”. “order” defines whether the posts will be displayed in ascending or descending order, by default they are displayed descending. “order_by” allows the developer to define how to sort the results by parameter, for example by post date, author or title.
In this case we will want to display posts in ascending order by the title of the book. Therefore once we have made the changes we should be able to see “Harry Potter” appear first followed by “Misery”.
$args = array( "order" => "asc", "order_by" => "title", "posts_per_page" => 2, "post_type" => "books" );
You should now definitely have a good feel for the power of WP_Query and how easy it is to display posts by different post_type. But before we round up this video blog we will put WP_Query to the test and see how it deals with taxonomies assigned to post_types.
Using WP_Query to filter by taxonomy
The custom post type “books”, currently features a “genre” taxonomy. Our aim is to filter the results so that it only shows the genre “fantasy”. To do this is extremely simple to do, add the name of the taxonomy as the “key” and then add the term as its “value”. Save and head over to your site and you should see only “Harry Potter” is showing, if we quickly change this to “horror”, you will be able to see “Misery” will only show.
$args = array( "order" => "asc", "order_by" => "title", "posts_per_page" => 2, "post_type" => "books", "genre" => "horror" );
Next weeks video blog will go far more in-depth into how you can filter by taxonomy using WP_Query, but todays tutorial should have given you the basic fundamentals of how to set up a WP_Query loop as well as how to filter your results.
Thats all for this weeks video blog, until next time. Bye bye.