Wordpress WP_Query wildcard in "key"

wordpress

Solution

Add a filter to the query to replace

meta_key = 'dates_$

with

meta_key LIKE 'dates_%

In functions.php:

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

add_filter( 'posts_where' , 'posts_where_dates' );

Your query remains the same as you had it. ie

$args = array(
    'post-type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'dates_$_participants',
            'compare' => '=',
            'value' => '"'.$user->ID.'"',  
        )
    )
);

Well hidden but documented here: https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where

Answer was edited due the changed behavior of esc_sql() in WordPress 4.8.3 https://make.wordpress.org/core/2017/10/31/changed-behaviour-of-esc_sql-in-wordpress-4-8-3/

Problem

I've got a simple question yet I cannot find the answer from looking on the web. With WP_Query, how is the "key" value from a "meta_query" treated? Can I use a wildcard? For instance: ``` $args = array( 'post-type' => 'post', 'meta_query' => array( array( 'key' => 'dates_%_participants', 'compare' => 'LIKE', 'value' => '"'.$user->ID.'"', ) ) ); $query = new WP_Query($args); ``` Notice the "%" in the 'key'

Original source