【发布时间】:2015-11-26 14:43:34
【问题描述】:
合并两个 wp_queries 的结果后,我尝试使用它们的 ID 数组作为新 wp_query 的 post__in 的参数。但由于某种原因,我得到了奇怪的结果(帖子总数不匹配)。据我了解,我无法将 post-ID 数组转换为 post__in 的正确格式(接受 ID 数组)。
到目前为止我做了什么:
echo count($first_query->posts); // returns 101
echo count($second_query->posts); // returns 201
$together = array_merge((array)$first_query->posts,(array)$second_query->posts);
echo count($together); // returns 302
var_dump($together); // returns: array(302) { [0]=> object(WP_Post)#6642 (24) { ["ID"]=> int(41) ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2005-04-01 05:49:22" ["post_date_gmt"]=> string(19) "2005-04-01 05:49:22" ["post_content"]=> string(0) "" ["post_title"]=> string(21) ...
到目前为止一切顺利。当数组之一为空时,我已转换为数组以避免 array_merge 返回 null。现在我正在尝试获取要在新 wp_query 中使用的 ID 数组,如下所示:
$result_args = array(
'post_type' => 'post',
'post__in' => $ids, // array(10,11,12 and so on)
'ignore_sticky_posts' => 1,
'post_per_page' => -1
);
$result = new WP_Query($result_args);
我一直在尝试以多种方式将 $together 转换为整数数组:
第一次尝试
$ids = wp_list_pluck($together, 'ID');
echo count($ids); // returns 302
var_dump($ids); // returns array(302) { [0]=> int(41) [1]=> int(44) [2]=> int(47) [3]=> int(89) ...
然而,在使用 $ids 作为 post__in 的参数后,wp_query $result 返回错误的帖子总数。
echo count($result); // returns 10
var_dump($result_args); // returns array(4) { ["post_type"]=> string(4) "post" ["post__in"]=> array(302) { [0]=> int(41) [1]=> int(44) [2]=> int(47) ... int(969) } ["ignore_sticky_posts"]=> int(1) ["post_per_page"]=> int(-1) }
第二次尝试
将 'fields' => 'ids' 添加到 $first_query 和 $second_query 后,它们都返回 ID 数组。
echo count($together); // returns 302
var_dump($together); // returns array(302) { [0]=> int(41) [1]=> int(44) [2]=> int(47) [3]=> int(89)
但同样,在使用数组 for post__in 后返回错误的结果:
echo count($result); // returns 10
第三次尝试
插入 ID 数组会返回一个字符串,post__in 无法处理。
echo count($result); // returns 0
也许我在寻找错误的方向并且还有其他问题,但我无法弄清楚是什么,所以任何帮助将不胜感激。
已解决
'post_per_page'
应该是 'posts_per_page' 现在一切正常。
【问题讨论】:
标签: wordpress