LoginSignup
0

More than 1 year has passed since last update.

【WordPress】サイドバーにカテゴリー一覧を表示して、今いるページと一致する場合はクラスを付与する

Last updated at Posted at 2022-12-09

やりたいこと

サイドバーにカテゴリー一覧を表示して、リンク先はアーカイブページにしたい!

要件としては、

  • 「All, Newsの子カテゴリー1, Newsの子カテゴリー2, Newsの子カテゴリー3」と並ぶ感じ
  • 全て遷移先はarchiveページでそれぞれ条件にあう投稿が表示されること
    • 現在いる場合はクラスを付与して背景色を変えたい
  • 「All」はカテゴリーNews(親カテゴリー4)その子カテゴリーを絞り込みの条件にしたい

実装したコード

sidebar.php

<aside id="secondary" class="widget-area">
	<h2 class="section-title">CATEGORY</h2>
	<ul class="category-list">
    // All
		<li class="cat-item all 
		<?php
		$url =
			(empty($_SERVER['HTTPS']) ? 'http://' : 'https://') .
			$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
		$pathArray = explode('/', $_SERVER["REQUEST_URI"]);
		$path = $pathArray[1] . '/' . $pathArray[2] . '/' . $pathArray[3];
        if ((!$pathArray[3] && $url == home_url('/category/news/')) || $path == 'category/news/page') {
			echo 'current-cat';
		}  ?>">
			<a href="<?php echo home_url('/category/news/') ?>">ALL</a>
		</li>
		// News子カテゴリー一覧
		<?php
		$catid = get_the_category();
		$args = array(
			'child_of' => 4, //親カテゴリID
			'title_li' => '', //タイトルはつけない
		);
		wp_list_categories($args); ?>
	</ul>
</aside><!-- #secondary -->

解説

Allを見ている場合のパスは localhost://category/news または localhost://category/news/page/1 などになります。一致する場合はcurrent-catクラスを付与します。

ページネーションで遷移した場合URLは localhost://category/news/page/1 のようにカテゴリー名の次に page 、その次にページネーション番号がきます。

URL全体の比較でも良いのですが、ページネーションで遷移したページの場合、数値が変動するので面倒。

プロトコルとホストはなしでパスの比較したい部分だけを取り出して条件分岐に使用します。

ちなみに、現在アクセスしているページのパスを取得するコードが以下になります。

	$url =
		(empty($_SERVER['HTTPS']) ? 'http://' : 'https://') .
		$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

ニュース一覧のURLはlocalhost://category/news です。

URLのパスの category/news が一致しているかで条件分岐します。

ニュース一覧のページネーション遷移時のURLはlocalhost://category/news/page/1 などです。

URLのパスの /category/news/page/  が一致しているかで条件分岐します。

// pathを取得し''
$pathArray = explode('/', $_SERVER["REQUEST_URI"]);
$newsCatPath = $pathArray[1] . '/' . $pathArray[2];
$newsChildCatPath = $pathArray[1] . '/' . $pathArray[2] . '/' . $pathArray[3];
if ((!$pathArray[3] && $url == home_url('/category/news/')) || $path == 'category/news/page') {
			echo 'current-cat';
		}

1行目の$_SERVER["REQUEST_URI"] でURLのパスを取得し、 explod()で「/」を区切りに配列にします。

2行目、3行目で一致させるパスと比較できるよう、配列にしたパスの必要な部分だけを結合させて加工します。

子カテゴリーに page とあった場合は条件を変える必要ありです。

4行目でそれぞれ条件を比較しています。どちらかの条件に一致した場合は current-cat クラスを出力し、クラスの付与を行います。

おわりに

サイドバーにこだわってたけどもしかして普通search.phpとかでやるのかも…?

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0