WordPressで固定ページ一覧を取得する
WordPressでナビゲーションが固定されていれば手書きでも良いのですが、ページ追加で自動展開されるナビゲーションにする場合は固定ページ一覧が欲しいときが有ります。
PHPソース
$args = array(
'post_type' => 'page',
);
$page = get_pages( $args );
$naviArray = array();
foreach($page AS $array){
if($array->post_parent == 0){ //親ページは0
$naviArray[$array->ID] = array(
'ID' => $array->ID
, 'post_title' => $array->post_title
, 'post_name' => $array->post_name
);
}else{
$naviArray[$array->post_parent]['child'][] = array( //子ページは親ページ配列に追加
'ID' => $array->ID
, 'post_title' => $array->post_title
,'oya_postname' => $naviArray[$array->post_parent]['post_name']
);
}
}
結果はこんな感じです。
Array
(
[5] => Array
(
[ID] => 5
[post_title] => MENU 1
[post_name] => menu1
[child] => Array
(
[0] => Array
(
[ID] => 17
[post_title] => CHILD1-1
[oya_postname] => menu1
)
[1] => Array
(
[ID] => 19
[post_title] => CHILD1-2
[oya_postname] => menu1
)
[2] => Array
(
[ID] => 21
[post_title] => CHILD1-3
[oya_postname] => menu1
)
)
)
[7] => Array
(
[ID] => 7
[post_title] => MENU 2
[post_name] => menu2
[child] => Array
(
[0] => Array
(
[ID] => 23
[post_title] => CHILD2-1
[oya_postname] => menu2
)
[1] => Array
(
[ID] => 25
[post_title] => CHILD2-2
[oya_postname] => menu2
)
)
)
[9] => Array
(
[ID] => 9
[post_title] => MENU 3
[post_name] => menu3
)
)
ナビゲーションに外部URLを追加したい
$naviArray[7]['child'][100] = array(
'ID' => null
, 'post_title' => 'Googele'
, 'url' => 'https://www.google.co.jp/'
);
親のID配列にこんな感じで追加してやると子に入ります。後はheader.phpなんかで展開してやれば良いかなっと。
配列へURLも一緒に加える場合はこんな感じで。
$naviArray[$array->ID] = array(
'ID' => $array->ID
, 'post_title' => $array->post_title
, 'post_name' => $array->post_name
, 'url' => get_bloginfo('url').'/'.$array->post_name
);




