WordPress is great for displaying your website content. It automatically knows how to retrieve (using queries) and display (using templates) blog posts and website pages. The generic query is enough for these tasks. But what if you wanted more? For example, you want to display related posts on the same page as a single post, or you want to display custom taxonomies, or you want to pull data from a custom table. To do this, you change the default query. Read on to discover how to use custom queries to control the data retrieved from your WordPress database.

Create a new query

Creating a new query is typically a two-step process. First, you set the parameters for the query, then you call the custom query. To create a custom query, you will have to dig into the code a little. Let’s say you want to change the number of posts per page for a certain category. Create a variable to hold the results from the query:

$new_query = new WP_Query( array(

    ‘category_name’ => ‘records’, //show posts from the ‘records’ category

) );

Then use the variable $new_query in the WordPress loop to display the results. The above code will show posts from the category ‘records’.

Don’t forget to reset the loop when done displaying the new query.

wp_reset_postdata();

The key is the parameters

The magic is in the parameters. The following lists some of the more popular parameters. You can find the full list in the WordPress codex.

'author_name' => 'Barry' //posts written by Barry

'author' => '2,6,17,38' //posts from multiple authors

'author' => -12 //use the minus sign to exclude

'tag' => 'cooking'. //posts with a tag of cooking

Want to get technical? Here is an example using multiple parameters.

$args = array(

    'post_type' => 'post',

    'tax_query' => array(

        array(

            'taxonomy' => 'people',

            'field'    => 'slug',

            'terms'    => 'bob',

        ),

    ),

);

Get unlimited results

As you can see, custom queries can get complicated It all comes down to the query parameters. For example, give me a list of posts with a category of ‘fish’, a taxonomy of ‘recipe’, ordered by publish date (newest to oldest). Want multiple queries on the same page? Yes, you can write a custom query for that. With custom queries, the possibilities are limitless. If you can think it, you can write a custom query for it.

Want to go even deeper? How about pulling data from a custom table? Yes, you can do that as well. Custom WordPress queries give you a powerful method of making your website display content in unique ways. If you want your WordPress website to do more, then use custom queries to control the data retrieved from your WordPress database.

Need help creating a custom query?

Let’s chat.

Share This