试试这个,WP_Query
不需要关系,只需使用比较部分IN
$user_ids = array(60, 61, 62, 63);
$args = array(
'post_type' => 'post',
'meta_key' => 'likes',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'rand',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'likes',
'value' => $user_ids, //array
'compare' => 'IN',
)
)
);
$query = new WP_Query($args);
请参阅上面给出的示例“时间参数”标题WP_Query
或者通过 get_posts 试试这个
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'rand',
'meta_query' => array(
array(
'key' => 'likes',
'value' => $user_ids,
'compare' => 'IN'
)
)
);
$posts = get_posts($args);
或者通过自定义查询,您可以执行以下操作
global $wpdb;
$liked_posts=$wpdb->get_results("SELECT * FROM `wp_posts` WHERE
post_type='post' AND post_status ='publish' AND ID
IN(
SELECT post_id FROM `wp_postmeta` WHERE meta_key='likes'
AND meta_value IN (".join(',',$user_ids).")
) ORDER BY RAND()");
也不要将 id 数组存储在一行中,而是循环遍历 ids 数组并手动规范您的喜欢数据不要将数据序列化到数据库字段中。这就是Database_normalization的用途,并将每个 id 插入新行,因为
Wordpress 将元值存储为字符串。当您传递
update_post_meta
一个数组时,它会自动将其转换为字符串。您需要做的是unserialize
当您尝试读取数据但在 mysql 中您不能unserialize
在查询中列数据,因为 mysql 不涉及 php 的序列化
$likes = array(61, 62);
foerach($likes as $l){
update_post_meta($post->ID, "likes", $l);
}
以下是您在赏金评论中要求的查询
如果给出 $wpdb 答案,请详细说明如何考虑类别(包括和排除),并忽略 ID 数组的帖子
$liked_posts=$wpdb->get_results("
SELECT * FROM `wp_posts` wp
INNER JOIN `wp_term_relationships` wtr ON (wp.`ID`=wtr.`object_id`)
INNER JOIN `wp_term_taxonomy` wtt ON (wtr.`term_taxonomy_id` =wtt.`term_taxonomy_id`)
WHERE wp.post_type='post' AND wp.post_status ='publish' AND wp.ID
IN(
SELECT post_id FROM `wp_postmeta` WHERE meta_key='likes'
AND meta_value IN (".join(',',$user_ids).")
) AND wp.ID NOT IN (100,101,102)
AND wtt.`term_id` IN(1,2,3) AND wtt.`term_id` NOT IN (4,5,6,)
ORDER BY RAND() ");
我已经使用了INNER JOINs
onwp_term_relationships
并且 wp_term_taxonomy
表格wp_term_relationships
存储了帖子的关系和类别的分类,并且表格wp_term_taxonomy
具有类别的分类以及类别 ID
这是涵盖
1. 类别(包括和排除)
AND wtt.`term_id` IN(1,2,3) AND wtt.`term_id` NOT IN (4,5,6,)
2.忽略ID数组的帖子
AND wp.ID NOT IN (100,101,102)
or $postids =array(100,101,102);
AND wp.ID NOT IN (".join(',',$postids).")