header.phpでシックハック!!
今までget_the_category()で情報を採っていたのですが、
親カテゴリーページの情報がなぜか子カテゴリーの情報になってしまう・・・
一日考えても埒が明かず。
get_the_category()の変わりにget_queried_object_id()を使用することに。
あっという間に解決しました♪
get_the_category()の場合
<?php if(is_category()|| is_single()){ $category = get_the_category();//投稿データのカテゴリー情報を取得する。 if(isset($category, $category[0])) { $cat_id = $category[0]->term_id; $cat_name = $category[0]->cat_name; //$cat_slug = $category[0]->category_nicename; $cat_slug = $category[0]->slug; $cat_description = $category[0]->category_description; $cat= $category[0]; $parent_id= $category[0]->category_parent;// 親カテゴリーのID取得 // 親カテゴリーがあったら if ( $parent_id != 0 ) { $parent_category_id = $parent_id; $parent_category = get_term_by( 'id', $parent_category_id, 'category' ); if ( $parent_category ) { $parent_category_slug = $parent_category->slug; } } } } ?>
get_queried_object_id()の場合
$cat = get_queried_object_id(); // 現在のカテゴリーを取得 $current_category = get_category( $cat ); // 現在のカテゴリーオブジェクトを取得 $cat_slug = $current_category->slug; // 現在のカテゴリースラッグ $cat_id = $current_category->term_id; // 現在のカテゴリーID取得 $cat_name = $current_category->name; // 現在のカテゴリーの名前を取得 $cat_description = $current_category->description;// 現在のカテゴリーの説明を取得 // 親カテゴリーがある場合 if ( $current_category->parent ) { $parent_category = get_category( $current_category->parent ); $parent_id = $parent_category->term_id; //親カテゴリーID取得 $parent_name = $parent_category->name; //親カテゴリーの名前取得 $parent_slug = $parent_category->slug; //親カテゴリーのスラッグ取得 } }
親カテゴリーがあった場合
<?php if($current_category->parent):?> ・・・親カテゴリーのある場合 <?php endif; ?>