「カレンダー」ウィジェットにカテゴリーラベルと同じ背景色を表示する方法

Cocoonカスタマイズ集
この記事は約4分で読めます。
記事内に広告が含まれています。

はじめに

WordPress標準の「カレンダー」ウィジェットは、日付ごとの投稿の有無を確認できる便利なツールです。
しかし標準設定では、投稿されたカテゴリーまでを一目で判別することができません。

そこで、カレンダーの日付リンクにカテゴリーラベルと同じ色を反映します。
なお、該当日に複数の投稿がある場合は、その日に公開された最新の投稿のカテゴリーのラベル色を表示します。

この記事では、この方法について説明します。

完成イメージ

2023-09
月 火 水 木 金 土 日
 123
45678910
11121314151617
18192021222324
252627282930  

実装手順

以下のコードをfunctions.phpに追加します。

add_filter('get_calendar', function ($calendar) {

  // 日付リンクから年月日を取得
  return preg_replace_callback(
    '#<a href="([^"]*/(\d{4})/(\d{2})/(\d{2})/)"#',
    function ($m) {

      // その日の最新の公開済み投稿を取得
      $posts = get_posts([
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'fields'         => 'ids',
        'date_query'     => [[
          'year'  => (int) $m[2],
          'month' => (int) $m[3],
          'day'   => (int) $m[4],
        ]],
      ]);

      $post_id = $posts[0];

      // Cocoonのメインカテゴリーを取得
      $cat_id = function_exists('get_the_page_main_category')
        ? (int) get_the_page_main_category($post_id)
        : 0;

      // メインカテゴリーがなければ最初のカテゴリーを取得
      if (!$cat_id) {
        $cats   = get_the_category($post_id);
        $cat_id = $cats ? (int) $cats[0]->term_id : 0;
      }

      // カテゴリーがなければ処理対象外
      if (!$cat_id) {
        return $m[0];
      }

      // カテゴリークラスを設定
      return '<a class="cat-label cat-label-' . $cat_id . '" href="' . $m[1] . '"';
    },
    $calendar
  );
});


// フロント用JS・CSSを追加
add_action('wp_enqueue_scripts', function () {
  ob_start();
  ?>
  .wp-calendar-table .cat-label {
    border: unset;
    font-size: unset;
    max-width: unset;
    padding: unset;
    position: unset;
  }

  .wp-calendar-table #today .cat-label {
    color: unset;
  }

  .wp-calendar-table td a:hover {
    color: unset;
  }
  <?php

  $handle ='calendar-color';

  wp_register_style($handle, false);
  wp_enqueue_style($handle);
  wp_add_inline_style($handle, ob_get_clean());
});

さいごに

今回紹介した方法を使えば、標準の「カレンダー」ウィジェットに投稿のカテゴリーカラーを自動的に反映させることができます。
これにより、読者は過去の記事を視覚的に探しやすくなり、ブログ全体の回遊率アップやデザイン性の向上が期待できます。

タイトルとURLをコピーしました