🍡
WordPressでページの一覧を表示する3通りの方法
記事や固定ページの一覧はnew WP_Query()やget_posts()で取得できます. しかし, 使い勝手がやや異なるので, 等価な書き方をメモしておきます. 以下の3通りの例文はいずれも同じ出力を与えます.
出力
i = 1, title1
i = 2, title2
i = 3, title3
found = 3
WP_Query()とwhile文
WP_Query()はオブジェクトを返すのでnewを付けます. while文と組み合わせて使います. この$query->the_post()があるおかげでget_the_title()やget_field("name");などを使うことができます. 記事数の取得に$found = $query->post_count;を, 番号を数えるために$i++を書いていますが, 不要な場合は消してしまって問題ありません.
<?php
$query = new WP_Query([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'desc',
'orderby' => 'date'
]);
$found = $query->post_count;
$i = 0;
if ($query->have_posts()) : while ($query->have_posts()) : $i++; $query->the_post();
?>
<p>i = <?php echo $i;?>, <?php echo get_the_title();?></p>
<?php endwhile; endif; ?>
<p>found = <?php echo $found?></p>
get_posts()とforeach文
get_posts()は配列を返すのでnewは不要です. foreach文やfor文と組み合わせて使います. $query->the_post()に相当する文として, setup_postdata($post)が必要です. これが無いとget_the_title()等の関数が使えません. 記事数の取得にはcount()を用います.
<?php
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'desc',
'orderby' => 'date'
]);
$found = count($posts);
$i = 0;
foreach ($posts as $post) : $i++; setup_postdata($post);
?>
<p>i = <?php echo $i;?>, <?php echo get_the_title();?></p>
<?php endforeach; ?>
<p>found = <?php echo $found?></p>
get_posts()とfor文
foreach文の時と同様に, setup_postdata($post)が必要です. また, PHPの配列の添え字は0始まりなので気を付けてください. 配列なので$post=$posts[$i]のように要素を取得しています.
<?php
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'desc',
'orderby' => 'date'
]);
$found = count($posts);
for ($i=0; $i<$found; $i++) : $post=$posts[$i]; setup_postdata($post);
?>
<p>i = <?php echo $i+1;?>, <?php echo get_the_title();?></p>
<?php endfor; ?>
<p>found = <?php echo $found?></p>
まとめ
get_the_title()やget_field("name");などの関数を使うためには,
-
new WP_Query()では$query->the_post() -
get_posts()ではsetup_postdata($post)
が必要です.
Discussion