Unfortunately you cannot perform a meta_query
using a LIKE
comparison on the meta_key
value when using WP_Query
. I’ve been down this road…
Instead you have a couple other options if you want to maintain like status relationships as post meta and not user meta and or meta in a custom table.
Option 1
- requires no modification of your meta schema
- uses
wpdb
class to perform a custom query
Example:
//when a user likes a post...
$current_user_id = get_current_user_id();
add_post_meta($current_user_id, "like_status_{$current_user_id}", 1, false);
//later in the request...
global $wpdb;
$results = $wpdb->get_results(
"
SELECT meta_key
FROM {$wpdb->prefix}postmeta
WHERE meta_key
LIKE 'like_status_%'
",
ARRAY_N
);
$results = array_map(function($value){
return (int) str_replace('like_status_', '', $value[0]);
}, $results);
array_walk($results, function($notify_user_id, $key){
//apply to all users except the user who just liked the post
if ( $notify_user_id !== $current_user_id ) {
//notify logic here...
}
});
Note: logic could be simplified further if you wish.
Option 2
- requires you change your meta schema
- requires you store the user id as the meta value
- allows you to use
WP_Query
along withmeta_query
Option 2 requires that you change your meta key from like_status_{user_id}
to something universal such as like_status
or liked_by_user_id
where in turn instead of storing the value of 1
against the key, you instead store the user’s id as the value.
//when a user likes a post...
$current_user_id = get_current_user_id();
add_post_meta($current_user_id, "liked_by_user_id", $current_user_id, false);
//later in the request
$args = array(
'post_type' => 'post', //or a post type of your choosing
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'liked_by_user_id',
'value' => 0,
'type' => 'numeric'
'compare' => '>'
)
)
);
$query = new WP_Query($args);
array_walk($query->posts, function($post, $key){
$user_ids = get_post_meta($post->ID, 'liked_by_user_id');
array_walk($user_ids, function($notify_user_id, $key){
//notify all users except the user who just like the post
if ( $notify_user_id !== $current_user_id ) {
//notify logic here...
//get user e.g. $user = get_user_by('id', $notify_user_id);
}
});
});