0

I am trying to get the post meta with meta query where value is an array of key value pairs.

 $user_id = '123';

  $arr = array();

  $arr['a'] => "somevalaaa" ;
  $arr['user_id'] => $user_id ;
  $arr['c'] => "somevalyyy" ;

Adding post meta

  add_post_meta($review_post_id, 'key_of_post_meta', $arr );

Getting post meta (having user id same as $user_id) with meta query, where I am wrong ?

  $args = array(
     'post_type' => 'as_reviews',
     'posts_per_page' => -1,
     'post_status' => 'publish',
          'meta_query' => array(
              array(
                'key' => 'key_of_post_meta',
                'value' => array('user_id'=>$user_id),
                'compare' => 'IN',
               ),
            ),
       );



  $query = new WP_Query($args);
3
  • Why not create a for loop where every run changes the key and value in the query? Commented Apr 10, 2018 at 11:00
  • that is not the case Commented Apr 10, 2018 at 11:01
  • Please see previous questions and answers on the matter: wordpress.stackexchange.com/questions/16709/… Short version: This is a poor way to store data you intend to query, and you should store it differently. Commented Apr 10, 2018 at 11:05

1 Answer 1

1

The meta_query cannot be used to search value which are stored as serialized arrays. You can use it to search multiple values (meta-fields can have several values using the same key).

You need a different approach to solve your problem, this is what I suggest,

store your meta field with the user id as part of the key name,

add_post_meta($review_post_id, 'key_of_post_meta_'.$user_id, $arr );

next, retrieve your posts with,

$args = array(
     'post_type' => 'as_reviews',
     'posts_per_page' => -1,
     'post_status' => 'publish',
     'meta_key' => 'key_of_post_meta_'.$user_id
    );
  $query = new WP_Query($args);
4
  • hmmmm, I like your idea Commented Apr 10, 2018 at 11:37
  • let me try with that Commented Apr 10, 2018 at 11:37
  • @NickTaylor did u manage to get it to work?
    – Aurovrata
    Commented Apr 11, 2018 at 7:48
  • oh yes that works Commented Apr 12, 2018 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.