問題
Wordpressの親ページのリストと子ページのリストを分けるには?
解決策
- 親ページのみを「'post_parent' => 0」でループ処理します。
- ループ処理内にて、オプションを作成し「'post_parent' => 親ページのID」を設定し、「get_children」を構築します。
- 取得した「get_children」をforeachで回し、子ページ格納用の配列に入れていきます。
- ループ処理を終了したら、データを入れ終えた子ページ格納用の配列を回し、子ページのリストを構築します。
親ページと子ページを分ける。
WordPressの親ページと子ページを分けてリスト化したい場合に、親ページのリストと子ページのリストを分ける方法をご紹介します。
「’post_parent’ => 0」と「get_children」を活用する。
- 親ページのみを「‘post_parent’ => 0」でループ処理します。
- ループ処理内にて、オプションを作成し「‘post_parent’ => 親ページのID」を設定し、「get_children」を構築します。
- 取得した「get_children」をforeachで回し、子ページ格納用の配列に入れていきます。
- ループ処理を終了したら、データを入れ終えた子ページ格納用の配列を回し、子ページのリストを構築します。
<?php
$childlist = array(); // 子ページ格納用の配列
// ↓ 親ページのリスト作成
$args1=array(
'posts_per_page' => -1,
'post_type' => '投稿タイプ名',
'orderby' => 'menu_order',
'order' => 'DESC',
'post_parent' => 0 // 親を持たないページのみを対象にする = 親ページのみ
);
$my_query_args1 = get_posts( $args1 );
if( $my_query_args1 ):
?>
<ul>
<?php
global $post;
foreach ($my_query_args1 as $post): setup_postdata($post); // 親ページのループ処理スタート
// ↓ 現在のページの子ページの情報を取得し、子ページ格納用の配列に入れ込む
$args_child = array(
'post_parent' => $post->ID,
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'DESC',
'post_type' => '投稿タイプ名'
);
$childArray = get_children( $args_child );
if ( count( $childArray ) > 0 ) :
foreach ( $childArray as $child ) :
$childlist[] = $child;
endforeach;
endif;
// ↑ 現在のページの子ページの情報を取得し、子ページ格納用の配列に入れ込む
?>
<li><?php echo get_the_title(); ?></li>
<?php
endforeach; // 親ページのループ処理の終了
wp_reset_query();
?>
</ul>
<?php
// ↑ 親ページのリスト作成
?>
<?php
// ↓ 子ページのリスト作成
?>
<ul>
<?php
if ( count( $childlist ) > 0 ) :
foreach ( $childlist as $child ) : // 子ページのループ処理スタート
?>
<li><?php echo $child->post_title; ?></li>
<?php
endforeach; // 子ページのループ処理の終了
endif;
?>
</ul>
<?php
endif;
?>
<?php
// ↑ 子ページのリスト作成
?>
ポイント!
- 「‘post_parent’ => 0」で、親を持たないページ = 親ページのみを取得することができます。
- 「get_children」で、特定の親ページを持つ子ページの情報を取得することができます。
コメント