トップページの「カードタイプ切り替え」機能を追加する方法

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

はじめに

THE THORでは、トップページに「ワイドレイアウト」「カードレイアウト」「ノーマルレイアウト」の切り替えボタンを設置できます。

これと同様に、トップページにカードタイプ切り替えボタンを追加します。

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

Cocoon設定→インデックス→カードタイプは、以下のいずれかに設定してください。

  • デフォルト
  • 大きなカード
  • 縦型カード(2列)

完成イメージ

実装手順

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

/**
 * Cookie値とCocoonのカードタイプ名・アイコン・タイトルの対応表を取得
 *
 * @return array Cookie値とカードタイプ名・アイコン・タイトルの対応表
 */
function my_entry_card_type_map() {
  return [
    'ect-entry-card' => [
      'type'  => 'entry_card',
      'icon'  => 'dashicons-align-wide',
      'title' => 'エントリーカード(デフォルト)',
    ],
    'ect-vertical-card-2' => [
      'type'  => 'vertical_card_2',
      'icon'  => 'dashicons-screenoptions',
      'title' => '縦型カード2列',
    ],
    'ect-big-card' => [
      'type'  => 'big_card',
      'icon'  => 'dashicons-align-full-width',
      'title' => '大きなカード',
    ],
  ];
}


// Cocoon設定(インデックス)のカードタイプを変更
add_filter('theme_mod_entry_card_type', function ($value) {
  if (is_admin()) {
    return $value;
  }

  // クッキーのカードタイプを取得
  $map = my_entry_card_type_map();
  $key = sanitize_key($_COOKIE['my_entry_card_type'] ?? '');

  return $map[$key]['type'] ?? $value;
});


// テンプレート(一覧)を変更
add_action('cocoon_part_before__tmp/list', function () {
  $map = my_entry_card_type_map();

  // 現在のカードタイプを取得
  $key = sanitize_key($_COOKIE['my_entry_card_type'] ?? '');

  if (!isset($map[$key])) {
    $current_type = get_theme_mod('entry_card_type', 'entry_card');
    $key = array_search($current_type, array_column($map, 'type'), true);
    $key = $key !== false ? array_keys($map)[$key] : 'ect-entry-card';
  }

  ?>
  <form class="layout-switcher" id="layoutForm">
    <?php foreach ($map as $value => $item) : ?>
      <label class="layout-switcher__item" title="<?php echo esc_attr($item['title']); ?>">
        <input class="layout-switcher__input" type="radio" hidden name="layout" value="<?php echo esc_attr($value); ?>" <?php checked($key, $value); ?>>
        <span class="layout-switcher__icon dashicons <?php echo esc_attr($item['icon']); ?>"></span>
      </label>
    <?php endforeach; ?>
  </form>
  <?php
});


// フロント用JS・CSSを追加
add_action('wp_enqueue_scripts', function () {
  ob_start();
  ?>
  .layout-switcher {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }

  .layout-switcher__item {
    color: #ccc;
    cursor: pointer;
  }

  .layout-switcher__input:checked + .layout-switcher__icon {
    color: #333;
  }
  <?php

  $handle = 'my-layout-switcher';

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


  wp_enqueue_style('dashicons');

  ob_start();
  ?>
  jQuery(function ($) {
    // レイアウトが変更された場合
    $('input[name="layout"]').on('change', function () {
      // 選択したカードタイプをクッキーに登録
      document.cookie = 'my_entry_card_type=' + encodeURIComponent(this.value)
        + '; path=/; max-age=31536000; SameSite=Lax';

      location.reload();
    });
  });
  <?php
  wp_add_inline_script('jquery', ob_get_clean(), 'after');
});

さいごに

今回紹介した方法を使えば、THE THORのように、トップページにカードタイプの切り替えボタンを設置できます。
ユーザーにとって見やすいレイアウトを選べるようになるため、回遊率の向上や直帰率の改善にもつながります。

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