How to Create Custom Query for WordPress

WordPress has a default query which fetches posts and display it in descending manner. If you are working on any WordPress customisation, you would come across a requirement to fetch WordPress posts in customised manner such as Fetching last 10 posts, Fetching post having specific category or tag.

Fortunately, we dont have to write MySQL level queries to get required data (and that what makes WordPress special), we can call a WP_Query function by passing required fields as input, we can get required data. This logic has two parts.

  1. Query : The query will select WordPress posts from the MySQL database based on our instructions.
  2. Loop : It will output the post information on the page. Each instance of output array will have attributes such as post thumbnail, title, date, and author etc.

Here is simple structure to help you understand custom WP_Query

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}

 

You can customized the query as per your requirement.

<?php

// Creating array
$args = array( 
'posts_per_page' => 15, 
'orderby' => 'date', 
'order' ='ASC'
);
// Initiate the custom query
$custom_query = new WP_Query( $args );

?>

By Default, it will search for posts, if you want to search for specific custom post type, you can simply add a parameter in array

<?php

// Creating array
$args = array( 
'post_type' => 'vehicle',
'posts_per_page' => 15, 
'orderby' => 'date', 
'order' ='ASC'
);
// Initiate the custom query
$custom_query = new WP_Query( $args );

?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.