Using wp_query to expand your WordPress Site’s Functions

Written by Pressable on
wp_query

Isaac CastilloToday’s guest blog post was written by Isaac Castillo. Isaac is the founder of Echo Design Solutions, a San Antonio-based WordPress and WooCommerce development company.


 

WordPress developers are constantly looking at ways to improve the functionality and performance of their clients’ sites. To aid in this effort, WordPress includes an extensive library of functions that can be used to add features and functionality to a site.  If, for example, you want to grab the title of a blog post within The Loop, which is PHP code that WordPress processes and displays on the current page, you can use the function the_title(). You can similarly use the function the_content() to retrieve the content of a blog post or retrieve post categories using the function get_categories().

Although WordPress has functions for just about everything you could want to do with a site, there will inevitably come a time when you’ll need to perform a task that can’t be handled using WordPress’ built-in functions. Consider, for example, how you might query data coming into the Advanced Custom Fields plugin and return that data for a post. To perform the query in this example, you’d need to look outside of WordPress’ built-in functions. WordPress includes a class that enables you to retrieve information from the WordPress database within The Loop using a custom query with custom parameters. This class is called WP_Query and, as you push further into developing on WordPress, you should become familiar with this valuable tool for developers.


My team and I recently completed a Python to WordPress migration for a client. The project required so many customizations and custom post types that we looked outside of WordPress’ built-in functions to target the exact information that we needed. In this case, the client needed their site to show only current events, meaning that it needed to reference the date that an event would take place.

how to use wp_query in wordpress
The site’s interface permits visitors to view a list of events by date

WordPress includes a function, get_the_date();, which returns the date that an event was created or input. Because this function is limited to the event’s creation date, it would not suffice for our project. We used Advanced Custom Fields to create a custom field that would allow us to track the date that any particular event takes place. Using WP_Query, we were able to write a custom query that pulled events based on the custom event field. The end result was that the site’s visitors could view a list of events that were either currently taking place or were scheduled to take place in the future.

The basic principle of working with WP_Query is to get information from the database in a way that can be looped as though it were retrieved using built-in WordPress functions. An added benefit of writing custom queries using WP_Query is that, by setting up helper functions, you can significantly extend WordPress’ functionality. To give you a taste of WP_Quuery in action, I’ve shared a sample query below based on my team’s recent Python to the WordPress migration project.

 

$args = array( 
    'orderby'        => 'date',
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        the_content();
    }
    wp_reset_postdata();
} else {
    echo '

Sorry, there are no posts to display

‘; }

You may notice that the query in this example looks a lot like a regular post loop query. The key difference is in the $args array, which allows you to specify the information that the query will pull from the database. Inside the $args, we can pass all sorts of criteria that will alter the outcome of the loop.

Once the query and loop have been set, we need to fill in the $args array so that it passes the correct arguments. If, for example, you wanted to get the custom post type for events that I described in my example, you could use the following arguments:

 

$args = array( 
    'orderby'        => 'date',
    'post_type'      => 'events',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
);

$the_query = new WP_Query( $args );

With this code, we are telling WordPress to query the database for a post type named events (the custom post type that we created) and only retrieve the events that have a published status. The variable posts_per _page can be used to specify the number of records that will be returned. Leaving it at -1 will return every applicable record.

At this point, we have retrieved the events post type, but we’re not done yet. We still need to process the data so that only the events with dates that are current and/or future will be displayed, and so that events with past dates will be ignored. This functionality can be achieved using the following adjusted query:

$time = current_time( 'timestamp' ); // Get current Unix timestamp

$args = array( 
'post_type' => ‘events',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'start_date',
'meta_value' => $time,
'meta_compare' => '>=',
'orderby' => 'meta_value',
'order' => 'ASC'
);

$the_query new WP_Query( $args );

As before, our query is grabbing the post type of events that are published and returning them all. The magic comes into play when we query the values from Advanced Custom Fields so that we can alter the results. In this example, the following arguments are used to achieve this functionality:

$time
Early in the script, we tied the time that the script loaded to a variable called $time as a Unix timestamp.

start_date
We want to target ‘meta_key’ => ‘start_date’. The start_date field, which is set in Advanced Custom Fields, is tied to our custom post type meta_key. We need this field to be able to query the data from Advanced Custom Fields.

meta_value
Here we are saying that we are looking for events with start_dates equal to the variable $time that we passed. But this isn’t our desired result as we’re interested in more than just events that are timed for today. We want events listed for today as well as the future. What do we do in this case?

meta_compare
The solution lies with meta_compare. We can use it to specify that, when we are looking for the value of meta_key, we want to compare it to something. Here we have >= which means we are looking for events greater than or equal to the value we set in meta_value. This is where WP_Query really shines as it allows us to add functionality that would otherwise be difficult to implement.

order
Finally, you can see that we are also able to sort the meta_value in ascending order. This arranges the events a clean chronological order.

My team’s recent Python to WordPress migration project afforded us the opportunity to put the powerful capabilities of WP_Query to good use. When you find yourself in a situation where WordPress’ built-in functions will not allow you to grab the data that you need in the format in which you need it, be sure to use custom queries with WP_Query. Just remember that with great querying comes great responsibility. And don’t forget to reset the post data when you’re done.

Tags: ,

An Automattic Invention A family of WordPress solutions.
Spooky Savings This October!15% OFF

Get 15% or More Off All New Hosting Plans with Promo Code GHOST