WordPress 4.8 を使用します。
カテゴリーページ(category.php)で親カテゴリーを取得
まずは親カテゴリーの情報を取得する必要があります。
カテゴリーページの場合は$catで現在のカテゴリーIDが取得できます。
なのでget_category($cat)とすればカテゴリー情報を取得できますね。
さらにparentがある場合はget_category($this_category->parent)というようにすれば親の情報を取得できます。
今回はサイドバーで表示したいのでglobalな変数($this_category)に取得したカテゴリーを入れてます。
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のカテゴリーは複数設定できるので配列を取得できますので、配列の最初のカテゴリーを取り出しましょう。
あとは先程と同じですね。
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_categoriesのchild_ofにIDを指定すると子カテゴリーを取得することができます。
<?phpglobal $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 ?>

