很遗憾,您无法执行meta_query
使用LIKE
比较meta_key
使用时的值WP_Query
. 我一直在走这条路。。。
相反,如果您想在自定义表中维护与post meta类似的状态关系,而不是用户meta和/或meta,那么您还有几个其他选项。
选项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要求您更改元架构,因为元值允许您使用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);
}
});
});