root@devinsight-hub: ~/create-wordpress-database-query
┌──(rootdevinsight-hub)-[~/blog]
└─#
cat create_a_wordpress_custom_query_with_wp_query.md

Create a WordPress Custom Query with WP_Query

┌──[ TABLE OF CONTENTS ]

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

┌──(rootdevinsight-hub)-[~/blog/comments]
└─#
tail -f comments.log

Leave a Comment

>
>
>

[SYSTEM] Navigation Initialization v1.2.5-GUIDE

Welcome, Agent. This interface is fully interactive. Here is how to navigate:

  • Type Commands: Use the input at the bottom. Try typing /work or /about and hit Enter.
  • Point & Click: Don't want to type? Hover and click any blue text or folders/ to view content.
  • HUD Controls: Use the + buttons at the top to close, minimize, or expand the terminal.
[PRO-TIP] Press Tab for command suggestions or type /help at any time.
root@kali: ~/exit
$ kill -9 portfolio
✕ Process terminated.
But great code never really stops.
Let's keep the conversation going.
> LinkedIn > GitHub