プログラミング

WP_Query()の使い方

制作 2025-01-14 07:12:08
最終更新 2025-01-14 09:51:05

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_queryhave_posts()メソッドがtrueを返せば次のコードを実行します。

while ( $the_query->have_posts() ) {

$the_queryhave_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_queryhave_posts()true以外の場合の実行コード。内容は省略。

wp_reset_postdata();

ループ後に条件を元に戻す関数です。

この操作はWP_Query()とセットで最後に必ず行います。