Wordpress meta_query how to use "like" comparison on meta_key

3k Views Asked by At

I have to get posts having a particular meta value for a dynamic meta key.

The meta key values will be:

  • _project_global_1_trend_link
  • _project_global_2_trend_link
  • etc...

The common text in meta key is trend_link. So I need to add like operator for meta key.

$posts = get_posts(array(
            'numberposts'   => -1,
            'post_type'     => 'projects',
            'meta_query' => array(
                array(
                   'key'     => 'trend_link',
                   'value'   => 10,
                   'compare' => 'LIKE'
                )
             )
        ));

By using this code I can apply like operator on meta_value.

But I need to apply like operator on meta_key.

Is there any way to apply like operator on meta_key.

Please help !!

2

There are 2 best solutions below

0
Zaronics On

If i'm correct you can add a dollar sign to the meta key for dynamic keys!

$posts = get_posts(array(
        'numberposts'   => -1,
        'post_type'     => 'projects',
        'meta_query' => array(
            array(
               'key'     => '_project_global_%_trend_link',
               'value'   => 10,
               'compare' => 'LIKE'
            )
         )
    ));
0
Valerii Vasyliev On

For this situation you can use a parameter "compare_key"

$posts = get_posts(array(
            'numberposts'   => -1,
            'post_type'     => 'projects',
            'meta_query' => array(
                array(
                   'key'     => 'trend_link',
                   'compare_key' => 'LIKE',
                   'value'   => 10,
                   'compare' => 'LIKE'
                )
             )
        ));