WP_Query在短码中异常:启用循环后陷入无限循环
问题场景
创建了名为lichthidau的WordPress自定义短码,代码如下。在Gutenberg短码块中使用[lichthidau](页面ID为106)时:
- 禁用while循环可正确显示符合条件的文章数量2;
- 启用while循环后,代码会获取当前页面ID(106)并陷入无限循环,预期仅显示两次数字2。
原代码:
add_shortcode('lichthidau', 'hp_lich_thi_dau'); function hp_lich_thi_dau( $atts ) { $output = ''; extract( shortcode_atts( array( 'posttype' => 'lich' ), $atts) ); $args = array( 'post_type' => $posttype, 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC', ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { $itemprop = ''; if ( 'microdata' === generate_get_schema_type() ) { $itemprop = ' itemprop="text"'; } echo '<div class="bang-lich">'; //while ( $the_query->have_posts() ) { $output = $the_query->found_posts; //} echo '</div>'; } wp_reset_postdata(); return $output;
原因分析
- 循环未推进查询指针:只写了
while ( $the_query->have_posts() )判断条件,但没有在循环内调用$the_query->the_post()来移动查询指针,导致指针永远停留在初始位置,循环无法终止,形成无限循环。 - 输出变量被覆盖:循环内每次直接将
$output赋值为总文章数,即便循环正常执行,最终$output也只会保留最后一次赋值的结果,无法实现多次输出的需求。 - 直接echo易引发冲突:短码内直接使用
echo输出HTML,不仅可能打乱WordPress的输出顺序,还容易意外触发全局查询内容(比如当前页面ID)。
修复方案
核心修复点
- 循环内必须调用
$the_query->the_post()推进查询指针,确保循环能正常终止; - 使用
.=运算符拼接$output内容,实现多次输出; - 将所有HTML内容统一拼接到
$output中再返回,符合WordPress短码的标准写法。
修复后的完整代码:
add_shortcode('lichthidau', 'hp_lich_thi_dau'); function hp_lich_thi_dau( $atts ) { $output = ''; extract( shortcode_atts( array( 'posttype' => 'lich' ), $atts) ); $args = array( 'post_type' => $posttype, 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC', ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { $itemprop = ''; if ( 'microdata' === generate_get_schema_type() ) { $itemprop = ' itemprop="text"'; } // 统一将HTML拼接到output,避免直接echo $output .= '<div class="bang-lich">'; while ( $the_query->have_posts() ) { $the_query->the_post(); // 关键:推进查询指针,终止循环 $output .= $the_query->found_posts; // 拼接内容,实现多次显示 } $output .= '</div>'; } wp_reset_postdata(); return $output; }
效果说明
修复后,循环会根据符合条件的文章数量(此处为2次)执行,每次输出总文章数2,最终页面会显示22,完全符合预期。
内容的提问来源于stack exchange,提问作者Hung Pham
相关产品推荐
相关产品推荐

