WP_Query()
を使ったループのWordPress公式リファレンスから参照したサンプルコードを分析しながら説明します。
<?php
// The Query.
$the_query = new WP_Query( $args );
// The Loop.
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . esc_html( get_the_title() ) . '</li>';
}
echo '</ul>';
} else {
esc_html_e( 'Sorry, no posts matched your criteria.' );
}
// Restore original Post Data.
wp_reset_postdata();
ここから各コードの説明をします。
$the_query = new WP_Query( $args );
$the_query
という新しいWP_Query
クラスのインスタンスをパラメータ$args
を指定して作ります。
query(クエリ)とはデータベースに問い合わせる条件群のことです。
不可算名詞なので配列として命名するときも慣用的にはthe_query
。
if ( $the_query->have_posts() ) {
have_posts()
はループの中でまだポストが存在しているかをbool
値で返すメソッドです。
$the_query
のhave_posts()
メソッドがtrue
を返せば次のコードを実行します。
while ( $the_query->have_posts() ) {
$the_query
のhave_posts()
がtrue
の間ループを実行します。
$the_query->the_post();
the_post()
はループ中の現在のポストの情報を用意するメソッドです。
このメソッドを発動することで以降のメソッドでループ中の個別のポストの情報を参照できます。
esc_html( get_the_title() );
get_the_title()
はループの中で現在参照しているポストのタイトルを取得します。
esc_html()
は個別ポストの情報参照をするメソッドとセットで使用します。詳しくは省略。
} else {
esc_html_e( 'Sorry, no posts matched your criteria.' );
}
$the_query
のhave_posts()
がtrue
以外の場合の実行コード。内容は省略。
wp_reset_postdata();
ループ後に条件を元に戻す関数です。
この操作はWP_Query()
とセットで最後に必ず行います。