Mangcoding

icon chat
Yayan Kurnia Akbar - Wednesday, 5 March 2025 - 10 months ago

The Ultimate Guide to Meta Query in Posts

single image
Photo by Bram Naus on Unsplash

In this post, Mangcoding will share The Ultimate Guide to Meta Query in Posts based on Meta Values, assuming that you already have a basic understanding of how WP_Query works in WordPress.

Before we begin, here are some very simple examples. Similar examples can be found in the WordPress Codex.

As you may know, all posts have metadata that you can fill in the Custom Fields metabox (this metabox can be hidden). So, for example, if you want to retrieve posts with the meta key show_on_homepage and the meta value on, you can do it as follows:

$rd_args = array(
    'meta_key' => 'show_on_homepage',
    'meta_value' => 'on'
);


$rd_query = new WP_Query($rd_args);

If not, and you need to query all posts except those that have this meta key-value pair, you can use the following parameter :

$rd_args = array(
    'meta_key' => 'show_on_homepage',
    'meta_value' => 'on',
    'meta_compare' => '!='
);


$rd_query = new WP_Query($rd_args);

Don’t forget that all the examples in this post are simplified, so some WP_Query parameters are missing, such as posts_per_page or post_type.

If you’re interested in other possible values for the meta_compare parameter, please check the parameter description below and compare, as both accept the same values.

This is a very simple example, just an introduction. But this post is about the meta_query parameter. This parameter allows us to create great post filters and advanced search scripts.

Link Mangcoding

Querying Posts by Meta Value

A simple example below allows you to retrieve all posts with a specific custom field value. In the following example, we fetch all posts with the custom field name ‘Color’ and the custom field value ‘white’. You can use the code below :

$rd_args = array(
    'meta_query' => array(
        array(
            'key' => 'color',
            'value' => 'white'
        )
    )
);


$rd_query = new WP_Query($rd_args);

If you look at the edit post page (in the admin area) for each post that matches the query, you will see the following section: ‘Custom Fields’.

Custom Field Mangcoding_Meta Query in Posts

And if you want to do the opposite—to get all posts except those with the meta key ‘color’ and the meta value ‘white’—you can use the following code :

$rd_args = array(
    'meta_query' => array(
        array(
            'key' => 'color',
            'value' => 'white',
            'compare' => '!='
        )
    )
);


$rd_query = new WP_Query($rd_args);

Link Mangcoding

Posts with Multiple Meta Values

Now, let’s try to retrieve all posts with the custom field ‘Color’ having the value ‘White’ OR ‘Green’ :

$rd_args = array(
    'meta_query' => array(
        array(
            'key' => 'color',
            'value' => array('white', 'green'),
            'compare' => 'IN'
        )
    )
);


$rd_query = new WP_Query($rd_args);

Now, how do we retrieve all posts (e.g., products in an online store) except for white products and green products :

$rd_args = array(
    'meta_query' => array(
        array(
            'key' => 'color',
            'value' => array('white', 'green'),
            'compare' => 'NOT IN'
        )
    )
);


$rd_query = new WP_Query($rd_args);

Link Mangcoding

How to Use ‘compare’ in meta_query

As you can see in the example below and in the following examples, there is a compare parameter in each query. Now, we want to show you which values are accepted and what they mean:

  • = (or not set) → Equal to
  • != → Not equal to
  • < → Less than
  • <= → Less than or equal to
  • > → Greater than
  • >= → Greater than or equal to, Example :
// the product price in this example is 2000 or more than 2000
$args = array(
    'meta_query' => array(
        array(
            'key' => 'price',
            'value' => 2000,
            'type' => 'numeric', // specify it for numeric values
            'compare' => '>='
        )
    )
);

LIKE – Allows searching for a specific string within the meta value. In the example below, the query returns all posts where the ‘first_name’ contains ‘John’, including ‘Johnny’, ‘Johnathan’, or even ‘somethingJohnsomething’ :

$args = array(
    'meta_query' => array(
        array(
            'key' => 'first_name',
            'value' => 'John',
            'compare' => 'LIKE'
        )
    )
);

Two more things: First – It is case-insensitive. Second – The wildcard symbol @ is not needed.

NOT LIKE – Similar to LIKE, but works in the opposite way—the meta value must not contain the given string.

IN – The post meta value must contain one of the values from the given array (see the example above).

NOT IN – The meta value must not contain any of the values in the given array.

BETWEEN – The post meta value must be within the specified range of values, Example :

// the product price is more than 2000 and less than 4000
$args = array(
    'meta_query' => array(
        array(
            'key' => 'price',
            'value' => array(2000, 4000),
            'type' => 'numeric',
            'compare' => 'BETWEEN'
        )
    )
);

It can also work for dates; you can see an example below.

NOT BETWEEN – Not within a specific range.

EXISTS (WordPress >= 3.5) – Checks if a meta value for a specific meta key exists or is empty/null.

$args = array(
    'meta_query' => array(
        array(
            'key' => 'misha_key',
            'compare' => 'EXISTS'
        )
    )
);

So, this actually checks whether a meta key exists—you don’t even need to provide a value with this parameter.

NOT EXISTS (WordPress >= 3.5) – Checks if the given meta key does not exist at all.

REGEXP (WordPress >= 3.7) – Allows you to compare the meta value using regular expressions, Example :

$args = array(
    'meta_query' => array(
        array(
            'key' => 'misha_key',
            'value' => '^[0-9]*$', // "misha_key" must be only numbers
            'compare' => 'REGEXP'
        )
    )
);

NOT REGEXP (WordPress >= 3.7) – Similar to REGEXP, but the meta value must not match the given regular expression.

RLIKE (WordPress >= 3.7) – A synonym for REGEXP.

Link Mangcoding

How to Use compare => BETWEEN for Dates in meta_query

You can also use meta_query to check if a custom field falls between two dates.

The most important thing to remember is that your date format must be in YYYY-MM-DD, YYYY/MM/DD, or a similar format (year, month, day, time).

Check how the date is stored in the database—if it is stored in a different format (e.g., just the day), the filter will not work unless you modify it in the database’s date column.

array( 'key' => 'sale_day', 'value' => array( '2018-01-01', '2018-01-09' ), 'compare' => 'BETWEEN' )

If the date is stored in UNIX timestamp format, for example: 1543391233, everything becomes much simpler :

$args = array(
    'meta_query' => array(
        array(
            'key' => 'sale_day',
            'value' => array(strtotime('2018-01-01'), strtotime('2018-01-09')),
            'type' => 'numeric',
            'compare' => 'BETWEEN'
        )
    )
);

Link Mangcoding

Multiple Meta Queries – Posts with Multiple Key-Value Pairs

Now, I will show you how to combine posts with multiple custom field values. But before that, you need to understand the relation parameter, which can accept two values: OR or AND (default).

// the 'color' is 'white' AND the 'price' is more than 2000 and less than 4000
$rd_query = new WP_Query(
    array(
        'meta_query' => array(
            'relation' => 'AND', // both of below conditions must match
            array(
                'key' => 'show_on_homepage',
                'value' => 'on'
            ),
            array(
                'relation' => 'OR', // only 'color' OR 'price' must match
                array(
                    'key' => 'color',
                    'value' => 'white'
                ),
                array(
                    'key' => 'price',
                    'value' => array(2000, 4000),
                    'type' => 'numeric',
                    'compare' => 'BETWEEN'
                )
            )
        )
    )
);

As you can see in the meta_query above, we are using multiple relations.

Link Mangcoding

How to Sort Posts by Meta Value (orderby and order Parameters)

I will show you various examples of how you can sort your posts by meta value. First, take a look at this simple code example, where we don’t even use a meta query :

$args = array(
     'meta_key' => 'misha_key',
     'orderby' => 'meta_value'
);

Now, let’s say the misha_key only contains numeric values; we can slightly modify our code for that case

$args = array( 
      'meta_key' => 'misha_key', 
      'orderby' => 'meta_value_num' 
);

But how do we use it together with a meta query? It’s simple—just modify the code as follows :

$args = array(
    'meta_query' => array(
        'misha_clause' => array(
            'key' => 'misha_key',
            'compare' => 'EXIST'
        )
    ),
    'orderby' => 'misha_clause'
);

Link Mangcoding

How to Query with Two or More Meta Keys

Yes, this query method has been used since WordPress version 4.2.

$args = array(
    'meta_query' => array(
        'relation' => 'AND',
        'price_clause' => array(
            'key' => 'price',
            'value' => array(2000, 4000),
            'type' => 'numeric',
            'compare' => 'BETWEEN'
        ),
        'misha_clause' => array(
            'key' => 'misha_key',
            'compare' => 'EXISTS'
        ),
    ),
    'orderby' => array(
        'price_clause' => 'ASC',
        'misha_clause' => 'DESC'
    ),
);

So, first, we sort the posts in ascending order by price_clause, and then we sort the posts in descending order by misha_clause.

That’s the explanation of The Ultimate Guide to Meta Query in Posts that Mangcoding can share. Hopefully, this article is useful and provides new insights for you. If you have constructive feedback or suggestions, feel free to leave a comment or contact us via email and Mangcoding’s social media.

Source : Rudrastyh.com

Link Copied to Clipboard