在 WordPress 主題開發中,有時需在主要迴圈開始前「提前進入」迴圈以取得特定資料(如作者資訊、分類標題等)。但 WordPress 預設單頁面僅執行一次主迴圈,若提前呼叫 the_post() 移動指標,後續的主迴圈將從「第二篇文章」開始,導致首篇文章遺漏。rewind_posts() 正是為了解決此問題而設計的內建函數。
<?php rewind_posts(); ?>
have_posts() / the_post() 可從頭遍歷。<?php if ( have_posts() ) : the_post(); // 提前進入迴圈取得作者名稱
echo get_the_author();
rewind_posts(); // 關鍵:重置指標回到第一篇
while ( have_posts() ) : the_post(); // 正式主迴圈開始
get_template_part( 'content', get_post_format() );
endwhile;
endif; ?>
此範例展示:先取得作者顯示名稱,隨即呼叫 rewind_posts(),確保後續主迴圈完整輸出所有文章。
wp_reset_postdata() 使用,確保全域 $post 變數正確。用於分類/標籤彙整頁面,直接取得目前頁面的分類或標籤名稱,不依賴主迴圈,亦不可置於迴圈內。
<?php single_cat_title( $prefix, $display ); ?>
$prefix:標題前綴字串。$display:true 直接輸出,false 回傳字串。範例(category.php):
<?php printf( __( 'Category Archives: %s', 'twentyeleven' ),
'<span>' . single_cat_title( '', false ) . '</span>' ); ?>
rewind_posts() 雖簡單,卻是掌控迴圈流程的關鍵。善用它能避免「文章漏顯」、「重複顯示」等常見 Bug,讓主題邏輯更穩健。