
一番階層が上のページスラッグ名を取得すると、ページ判定などで便利
固定ページは、親ページ、子ページ、孫ページといった形で階層化が出来る。子ページはもちろん、孫ページで、親ページのスラッグ名を取得して表示したい場合がある。
その場合の実装方法を記述する。
サンプルコード functions.phpに下記を記述
<?php function ps_get_root_page( $cur_post, $cnt = 0 ) { if ( $cnt > 100 ) { return false; } $cnt++; if ( $cur_post->post_parent == 0 ) { $root_page = $cur_post; } else { $root_page = ps_get_root_page( get_post( $cur_post->post_parent ), $cnt ); } return $root_page; } ?>
サンプルコード テンプレート内の表示したい箇所に下記を記述
<?php $root_slug = ps_get_root_page( $post ); $root_slug = $root_slug->post_name; echo $root_slug ?>