w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
WordPress Meta Query Arrays

You're going to run into problems with your current approach because, as you note, the ids are saved as serialized arrays in a single field. An easier approach would be to save each like as a single postmeta entry. So meta_key = "like" and meta_value = user ID.

So for storing the likes switch from update_post_meta to add_post_meta:

/** The fourth parameter, false, tells WP that there can be
  * post_meta entries with the same meta_key. It's false by default, just
  * here for reference
add_post_meta($post->ID, 'like', $user_id, false);

Then to get posts liked by a specific user you would just do:

$liked_posts = $wpdb->get_results("SELECT post_id FROM
              WHERE meta_key = 'like' AND meta_value = $user_id");

To get results for a number of users at once, like user ID 4, 23, 39, etc.

$liked_posts_by_user = $wpdb->get_results("SELECT meta_value
as user_id, 
         GROUP_CONCAT(post_id) as posts FROM {$wpdb->prefix}wp_postmeta 
         WHERE meta_value IN('22','23','24') GROUP BY user_id

That will give you results like:

  user_id    posts
   23         1
   25         2,40,3

So just replace the IN portion of the query with your array of user ids.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.