Create a WordPress Custom Query with WP_Query

Create a WordPress Custom Query with WP_Query

Depending on the Database, sometimes we need to create WordPress Custom database query. When we need to do custom query then don’t do direct database query because WordPress offers us a WP_Query function to create this query simply.

The Loop with WP_Query

We used this loop with WP_Query to get data from database. We create a query which return infinite number of post

//declare the post arguments
$args = array('posts_per_page' => -1, 'orderby' => 'title', 'post_type' => 'post',
    'order' => 'ASC');

And using this arguments with loop

//get post data with get_posts function
$custom_query = new WP_Query($args);


if ($custom_query->have_posts()) {
echo '<ul>';
while ($custom_query->have_posts()) {
$custom_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
echo 'No posts found';
}

/* Restore original Post Data */
wp_reset_postdata();

Remember to set wp_reset_postdata(); after each custom query.

Custom sorting

If you want the titles sorted alphabetically, set the $args:

$args = [
    'posts_per_page' => -1,
    'orderby'        => 'title',
    'order'          => 'ASC',
];

The versatile ‘meta_query’

$args = [
    'post_type'  => 'post',
    'meta_query' => [
        'relation' => 'OR',
        [
            'key'     => 'color',
            'value'   => 'orange',
            'compare' => '=',
        ],
        [
            'relation' => 'AND',
            [
                'key'     => 'color',
                'value'   => 'red',
                'compare' => '=',
            ],
            [
                'key'     => 'size',
                'value'   => 'small',
                'compare' => '=',
            ],
        ],
    ],
];

Github Link

Read More: How to Create WordPress Plugin from Scratch – Step-by-Step Guide, Easy Floating Share Button – Social Share WordPress Plugin, 5 Steps to Enhance WordPress Search with Autocomplete and AJAX, 6 Step of Version Control: Basic Git Command for Beginners, WordPress walker_nav_menu: Basic Usage of walker_nav_menu

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top
Theme Mode