遗憾的是,使用时,您无法对值进行meta_query
使用LIKE
比较。我走这条路...meta_key
WP_Query
相反,如果您要维护状态关系(如发布元数据)而不是用户元数据和/或自定义表中的元数据,则可以使用其他两种选择。
选项1
- 不需要修改您的元架构
- 使用
wpdb
类执行自定义查询
例:
//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...
}
});
注意:如果需要,可以进一步简化逻辑。
选项2
- 需要您更改元架构
- 要求您将用户ID存储为元值
- 允许您与
WP_Query
一起使用meta_query
选项2要求您将元密钥从更改like_status_{user_id}
为通用名称,例如like_status
或liked_by_user_id
,而不是1
针对密钥存储值而不是存储用户的ID作为值。
//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);
}
});
});