Perform a wildcard search in a WordPress meta query

If you need to run a WordPress meta query where the meta key starts, ends or contains a certain string, you can enable wildcard searches on your site.


When running a WP Query that includes a meta_query argument, you may want to conduct a LIKE search on meta keys; for example, if you wanted to retrieve all posts that are tagged with a meta field whose key starts with dates_. In MySQL, this would be written as WHERE meta_key LIKE 'dates_%' but how do we accomplish this with WordPress’ query structure?

The following code, added to your functions.php or equivalent, will modify the underlying MySQL query to include that LIKE operator when you include a meta_query containing the % wildcard parameter. You can of course amend the meta_key prefix of dates_ from the example below to suit your individual requirements.

/**
 * Allow wildcards in meta search
 */

function wildcard_meta_query( $where ) {    
    return str_replace( "meta_key = 'dates_%", "meta_key LIKE 'dates_%", $where );
}
add_filter( 'posts_where', 'wildcard_meta_query' );

Your WordPress queries will now support wildcard meta key searches, using the % character to denote a wildcard search. For example, dates_% will include posts that have a meta key beginning with dates_.

A wildcard search of %_dates on the other hand will look for meta keys that end with _dates, while a wildcard search of %dates% will look for any meta keys that contain the word ‘dates’.

If you’re amending the meta_query arguments to either of those other scenarios, you will need to amend the str_replace of the wildcard_meta_query() function above to make sure the find and replace matches what you’re looking to achieve.


$args = [
    'post_type' => 'post',
    'meta_query' => [
        [
            'key' => 'dates_%',
            'compare' => 'LIKE',
        ]
    ]
]

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones