WP_Query中post__not_in与posts_per_page失效问题求助
问题排查与修正方案
核心错误原因
你的WP_Query参数配置存在结构错误:post__not_in、posts_per_page、paged这些顶级查询参数被错误嵌套在了tax_query的子数组中,导致WordPress无法识别这些参数,因此排除当前文章和限制显示数量的逻辑完全失效。
其他次要问题
post_type设为any可能会包含无关文章类型,建议明确指定你的自定义文章类型名称- 循环中调用
$_post->ID,但$_post未定义,应使用get_the_ID() - HTML类名拼写错误:
clas="flex_accom"应为class="flex_accom" - 获取父分类时未处理变量未定义的边界情况
修正后的完整代码
<?php // 获取当前文章的accommodatie分类 $accotype = get_the_terms(get_the_ID(), 'accommodatie'); $parent_accotype_value = ''; if ($accotype && !is_wp_error($accotype)) { foreach ($accotype as $parent_accotype) { if ($parent_accotype->parent == 0) { $parent_accotype_value = $parent_accotype->term_taxonomy_id; break; // 找到父分类后停止循环,避免多父分类时覆盖 } } } // 仅当获取到父分类ID时执行查询 if (!empty($parent_accotype_value)) { $params = array( 'post_type' => 'your-cpt-slug', // 替换为你的自定义文章类型别名 'posts_per_page' => 3, 'post__not_in' => array(get_the_ID()), 'paged' => isset($paged) ? $paged : 1, 'tax_query' => array( array( 'taxonomy' => 'accommodatie', 'field' => 'term_taxonomy_id', 'terms' => $parent_accotype_value, ), ), ); $the_query = new WP_Query($params); if ($the_query->have_posts()) { echo '<div class="flex-container">'; while ($the_query->have_posts()) { $the_query->the_post(); echo '<div class="flex_accom">'; if (has_post_thumbnail()) { echo get_the_post_thumbnail(get_the_ID(), 'medium'); } echo '<h4>' . get_the_title() . '</h4>'; echo '</div>'; } echo '</div>'; } wp_reset_postdata(); } ?>
关键修改说明
- 将
posts_per_page、post__not_in、paged移到tax_query外部作为顶级参数,确保WordPress能正确解析 - 增加了分类获取的错误判断(
!is_wp_error),避免分类不存在时报错 - 替换
$_post->ID为get_the_ID(),确保循环中能正确获取当前文章ID - 修正了HTML类名拼写错误
- 增加了父分类ID非空判断,避免无效查询
内容的提问来源于stack exchange,提问作者Derek
相关产品推荐
相关产品推荐

