以前、wordpressのget_pagesで取得したページデータを元に、固定ページの子ページをループして出力するという記事を書きました。
wordpressで固定ページの子ページを取得してリスト表示する
今回query_postsとWP_Queryで子ページをループしてみます。こっちのほうが絶対簡単です。
query_postsで子ページを表示する
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php
$postsArg = array(
‘posts_per_page’ => –1 ,
‘post_type’ => ‘page’ ,
‘post_parent’ => $post–> ID //親ページのID
);
if($PostArg = query_posts($postsArg)){ //小ページがある場合
query_posts($postsArg);
if(have_posts()) {
while(have_posts()) {
the_post();
?>
ここにループしたいコンテンツ…
<?php }
} else { echo ‘<p>coming soon..</p>’;}
wp_reset_query();
?>
|
posts_per_pageに“-1”を指定して、すべて出力しています。
WP_Queryで子ページを表示する
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$postsArg = array(
‘posts_per_page’ => –1,
‘post_type’ => ‘page’
‘post_parent’ => $post–>ID, //親ページのID
);
$PostArg = new WP_Query($postsArg);
if($PostArg –> have_posts()){
while( $PostArg–>have_posts()){
$PostArg –> the_post();
?>
ここにループしたいコンテンツ…
<?php
}
} else { echo ‘<p>coming soon..</p>’;}
wp_reset_postdata();
}
|
query_postsに比べ他のループへの影響が少なく勝手の効くWP_Queryに最近はまっています。
ちょいちょい忘れる『WP_Query』の使い方 | 予習と復習
query_posts で指定できるパラメーター // understandard
WP_Queryの使い方をPHPコードにまとめた便利なコード・スニペット | notnil creation weblog
このあたりの記事が本当に役に立っています。感謝感謝。
こちらも。
とはいえど、query_postsも最後にwp_reset_query();をつけてリセットすればいうほど影響というか干渉もしないと思うのですが…
以上の2つは、ループに使う配列の要素に‘post_parent’=>$post->IDと書き、投稿自体のID(今回のケースだと、親ページのID)を使い、子ページをループしていますが、post_parentにページIDを指定することで、親ページ以外のページからでも一覧を見せることが出来ます!これは便利ですね。
でわ!