WP_Query中post_parent与post__in无法同时生效的解决办法
问题分析与解决方案
你的代码存在两个关键问题,导致post__in参数不生效甚至逻辑冲突:
- 参数类型错误:WordPress的
post__in要求接收数组格式的值,你直接传入单个$parentPostID,会被系统忽略。 - 逻辑冗余且矛盾:你已经通过
post_parent筛选出父ID为$parentPostID的子文章,同时又用post__in传入父文章ID,这会让查询试图寻找“既是该父文章的子文章,同时ID等于父文章ID”的内容——这显然不可能,这个参数完全没必要存在。
修正后的代码
$currentPostID = get_the_ID(); $parentPostID = wp_get_post_parent_id($currentPostID); if ($parentPostID) { $args = array( 'post_type' => 'post', 'post_parent' => $parentPostID, 'posts_per_page' => -1, 'post__not_in' => array($currentPostID) ); $query = new WP_Query($args); }
补充说明
如果你的真实需求是同时包含父文章本身和它的子文章,且排除当前文章,那需要先获取父文章ID+所有子文章ID的集合,再传入post__in,同时移除post_parent参数。但从原代码逻辑判断,你只是想获取当前文章的兄弟文章(同父的其他子文章),上面的修正代码就能满足需求,且是单查询的最优性能方案。
内容的提问来源于stack exchange,提问作者gassiopea
相关产品推荐
相关产品推荐

