bodyタグにページのスラッグを入れる 親ページがある場合は親ページのスラッグも入れる
グローバルナビの現在地表示とかでbodyタグに今のページ名をclassで入れておかないといけない
body_classはテンプレートタグの一種で好きなクラスをbody_class('class-name')とかで追加できるけどページごとに入れたいし親ページがある場合はその親のスラッグも入れたい
時に以下のように拡張する
//body_class にページスラッグ追加
function custom_body_class($slug) {
if ( is_singular() ) {
$post_type = get_query_var( 'post_type' );
if ( is_page() ) {
$post_type = 'page';
}
if ( $post_type && is_post_type_hierarchical( $post_type ) ) {
global $post;
$slug[] = esc_attr( $post->post_name );
if ( $post->ancestors ) {
$root = $post->ancestors[count($post->ancestors) - 1];
$root_post = get_post( $root );
$slug[] = esc_attr( $root_post->post_name );
}
}
}
return $slug;
}
add_filter('body_class','custom_body_class');
特定のページで追加でクラス入れたい時は以下になる
//body_class にページスラッグ追加
function custom_body_class($slug) {
if ( is_singular() ) {
$post_type = get_query_var( 'post_type' );
if ( is_page() ) {
$post_type = 'page';
}
if ( $post_type && is_post_type_hierarchical( $post_type ) ) {
global $post;
$slug[] = esc_attr( $post->post_name );
if ( $post->ancestors ) {
$root = $post->ancestors[count($post->ancestors) - 1];
$root_post = get_post( $root );
$slug[] = esc_attr( $root_post->post_name );
}
}
}
//スラッグがcontactの時にクラス名formpage追加
if(in_array('contact',$slug)) {
$slug[] = 'formpage';
}
return $slug;
}
add_filter('body_class','custom_body_class');
使い方
<body <?php body_class(); ?>>
header.phpに入れる スペースを開けること