説明
have_posts() は、ループ内で、まだ表示していない投稿が残っているかを判定する関数です。
基本構文
have_posts(): bool
引数
引数はありません。
戻り値
残っていれば true。
使い方(サンプル)
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_title();
}
}
注意点
the_post()とセットで使うのが基本のループの形です。
実務での使いどころ
- 投稿の一覧(ループ)を、表示するとき。
- まだ表示していない投稿が、あるかを、確認するとき。
よくあるミスと対処
- ループの中で、
the_post()を呼ばず、同じ投稿が、無限に繰り返される。 - サブクエリのループで、
have_posts()を使っている。サブクエリでは、$query->have_posts()を使う。 - ループの後に、サブクエリを使い、
wp_reset_postdata()を呼ばない。
NG例
while ( have_posts() ) {
the_title(); // the_post() がなく、無限ループになる
}
OK例
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_title();
}
}
使い分け早見表
| 関数 | 役割 |
|---|---|
have_posts() |
表示する投稿が、残っているかを確認する |
the_post() |
次の投稿を、取り出して、準備する |
wp_reset_postdata() |
サブクエリのあとに、元に戻す |
関連項目
the_post()、wp_reset_postdata()
公式リファレンス:have_posts() | Function | WordPress Developer Resources

コメント