タグ一覧から不要なタグを非表示する方法

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

はじめに

以前の記事では、特定のタグクラウドを非表示にする方法を紹介しました。

今回は、機能を拡張し、タグ一覧画面に「表示/非表示」の切り替えボタンを設置して、タグごとにタグクラウドへの表示・非表示を設定できるようにします。

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

完成イメージ

実装手順

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

// 管理画面一覧にカラムを追加
add_filter('manage_edit-post_tag_columns', function ($columns) {
  $columns['tag_visibility'] = '表示/非表示';

  return $columns;
});


// 管理画面一覧のカラムにデータを表示
add_filter('manage_post_tag_custom_column', function ($value, $column_name, $term_id) {
  if ('tag_visibility' !== $column_name) {
    return $value;
  }

  // 対象タームの非表示状態を判定
  $is_hidden = get_term_meta($term_id, 'my_hide_tag_cloud', true);
  
  // 非表示状態に応じてCSSクラスを設定
  $btn_class = ($is_hidden === '1') ? 'tag-vis-btn is-hidden' : 'tag-vis-btn is-visible';
  $btn_text  = ($is_hidden === '1') ? '非表示' : '表示中';

  return '<button type="button" class="button button-small ' . esc_attr($btn_class) . '" data-term-id="' . esc_attr($term_id) . '">' . esc_html($btn_text) . '</button>';
}, 10, 3);


// 管理画面用JS・CSSを追加
add_action('admin_enqueue_scripts', function ($hook_suffix) {
  if ($hook_suffix !== 'edit-tags.php') {
    return;
  }

  // 現在の管理画面のスクリーン情報を取得
  $screen = get_current_screen();
  if (!$screen || $screen->taxonomy !== 'post_tag') {
    return;
  }
    
  ob_start();
  ?>
  .tag-vis-btn {
    &.is-visible {
      border-color: #00a32a !important;
      color: #00a32a !important;
    }

    &.is-hidden {
      border-color: #d63638 !important;
      color: #d63638 !important;
    }
  }
  <?php
  wp_add_inline_style('wp-admin', ob_get_clean());

  // すべてのタグターム情報を取得
  $terms = get_terms(['taxonomy' => 'post_tag', 'hide_empty' => false]);
  $nonces = [];
  if (!is_wp_error($terms)) {
    foreach ($terms as $term) {
      $nonces[$term->term_id] = wp_create_nonce('tag_visibility_nonce_' . $term->term_id);
    }
  }

  $handle = 'tag-visibility-admin-js';

  wp_register_script($handle, '');
  wp_enqueue_script($handle);

  wp_localize_script($handle, 'tagVisData', [
    'ajaxurl' => admin_url('admin-ajax.php'),
    'nonce'   => wp_create_nonce('tag_visibility_common_nonce')
  ]);

  ob_start();
  ?>
  jQuery(document).ready(function($) {
    $(document).on('click', '.tag-vis-btn', function() {
      var $btn = $(this);
      var termId = $btn.data('term-id');

      $btn.prop('disabled', true);

      $.ajax({
        url: tagVisData.ajaxurl,
        type: 'POST',
        data: {
          action: 'toggle_tag_visibility_btn',
          term_id: termId,
          nonce: tagVisData.nonce
        },
        success: function(response) {
          $btn.prop('disabled', false);
          if (response.success) {
            var isHidden = response.data.is_hidden;
            if (isHidden === '1') {
              $btn.text('非表示').removeClass('is-visible').addClass('is-hidden');
            } else {
              $btn.text('表示中').removeClass('is-hidden').addClass('is-visible');
            }
          } else {
            alert(response.data || '更新に失敗しました。');
          }
        },
        error: function() {
          $btn.prop('disabled', false);
          alert('通信エラーが発生しました。');
        }
      });
    });
  });
  <?php
  wp_add_inline_script($handle, ob_get_clean());
});


// Ajaxアクションを追加
add_action('wp_ajax_toggle_tag_visibility_btn', function() {
  if (!isset($_POST['term_id']) || !isset($_POST['nonce'])) {
    wp_send_json_error('不正なリクエストです。');
  }

  // nonceチェック
  if (!wp_verify_nonce($_POST['nonce'], 'tag_visibility_common_nonce')) {
    wp_send_json_error('セキュリティチェックに失敗しました。');
  }

  // 権限チェック
  if (!current_user_can('manage_categories')) {
    wp_send_json_error('権限がありません。');
  }

  // 対象のタームIDを取得
  $term_id = intval($_POST['term_id']);

  // 現在のメタデータを取得
  $current_hidden = get_term_meta($term_id, 'my_hide_tag_cloud', true);
  $new_hidden = ($current_hidden === '1') ? '' : '1';

  if ($new_hidden === '1') {
    update_term_meta($term_id, 'my_hide_tag_cloud', '1');
  } else {
    delete_term_meta($term_id, 'my_hide_tag_cloud');
  }

  wp_send_json_success(['is_hidden' => $new_hidden]);
});


// タグクラウドのクエリを変更
add_filter('widget_tag_cloud_args', function($args) {
  // 非表示フラグが設定されているタームのIDリストを取得
  $hidden_terms = get_terms([
    'taxonomy'   => 'post_tag',
    'hide_empty' => false,
    'meta_query' => [
      [
        'key'     => 'my_hide_tag_cloud',
        'value'   => '1',
        'compare' => '='
      ]
    ],
    'fields'     => 'ids',
  ]);

  // 非表示タームが存在する場合の除外設定
  if (!empty($hidden_terms) && !is_wp_error($hidden_terms)) {
    if (isset($args['exclude']) && is_array($args['exclude'])) {
      // 既存の除外設定とマージして置換
      $args['exclude'] = array_merge($args['exclude'], $hidden_terms);
    } else {
      // 新規に除外設定を登録
      $args['exclude'] = $hidden_terms;
    }
  }

  return $args;
});

さいごに

今回紹介した方法を使えば、記事数の少ない重要なタグが埋もれてしまう問題を解消し、WordPressのタグクラウドを思い通りにコントロールできるようになります。
管理画面のタグ一覧からワンクリックで表示・非表示を切り替えられるため、運用の手間もかかりません。
サイトの回遊性を高めたい方や、特定のタグを優先して見せたい方は、ぜひ導入してみてください。

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