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);
  • Why not create a for loop where every run changes the key and value in the query? – Interactive Apr 10 '18 at 11:00
  • that is not the case – Nick Taylor Apr 10 '18 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. – Jacob Peattie Apr 10 '18 at 11:05
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);
| improve this answer | |
  • hmmmm, I like your idea – Nick Taylor Apr 10 '18 at 11:37
  • let me try with that – Nick Taylor Apr 10 '18 at 11:37
  • @NickTaylor did u manage to get it to work? – Aurovrata Apr 11 '18 at 7:48
  • oh yes that works – Nick Taylor Apr 12 '18 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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