WEBOPIXEL

WordPressで所属しているカテゴリーの子カテゴリー一覧を表示する

Posted: 2017.08.18 / Category: WordPress 

例えばグローバルナビに親カテゴリーがあり、それぞれのカテゴリーページにアクセスするとサイドバーに所属しているカテゴリーの子カテゴリーの一覧を表示したいという想定です。

Sponsored Link

WordPress 4.8 を使用します。

カテゴリーページ(category.php)で親カテゴリーを取得

まずは親カテゴリーの情報を取得する必要があります。
カテゴリーページの場合は$catで現在のカテゴリーIDが取得できます。
なのでget_category($cat)とすればカテゴリー情報を取得できますね。
さらにparentがある場合はget_category($this_category->parent)というようにすれば親の情報を取得できます。

今回はサイドバーで表示したいのでglobalな変数($this_category)に取得したカテゴリーを入れてます。

category.php

global $this_category;
// IDからカテゴリー情報を取得
$this_category = get_category($cat);

// 親カテゴリーがある場合取得
if ($this_category->parent) {
	$this_category = get_category($this_category->parent);
}

シングルページ(single.php)で所属しているカテゴリーの親を取得

シングルページではget_the_categoryでカテゴリー情報を取得できます。
WordPressのカテゴリーは複数設定できるので配列を取得できますので、配列の最初のカテゴリーを取り出しましょう。
あとは先程と同じですね。

single.php

global $this_category;

$cats = get_the_category();
// 最初のカテゴリーを取り出す
$this_category = $cats[0];

// 親カテゴリーを取得
if ($this_category->parent){
	$this_category = get_category($this_category->parent);
}

サイドバー(sidebar.php)で表示

最後にサイドバーで子カテゴリーの一覧を表示してナビゲーションを作成してみます。
get_categorieschild_ofにIDを指定すると子カテゴリーを取得することができます。

sidebar.php

<?php
global $this_category;
$categories = get_categories(array(
	'child_of' => $this_category->term_id,
	'taxonomy' => 'category'
));
if ($categories):
?>
<ul>
	<?php foreach($categories as $value): ?>
		<li><a href="<?= esc_url(get_category_link($value->term_id)) ?>"><?= esc_html($value->name) ?></a></li>
	<?php endforeach; ?>
</ul>
<?php endif; // $categories ?>