「ボタン」ブロックにクリック数を表示する方法

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

はじめに

投稿や固定ページにボタンを設置し、クリック時にその回数をボタン上へリアルタイム表示します。

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

完成イメージ

実装手順

以下の手順で実装します。

  • ラベル
    Gutenbergエディターでの設定
    Gutenbergエディター

    以下に手順を示します。

    1. 「ボタン」ブロックを配置します。
    2. 「ボタン」ブロックに高度な設定→HTMLアンカーにmy-btn-任意の文字と入力します。
      複数のボタンを配置する場合は、それぞれ重複しないユニークなアンカー名(例:my-btn-1、my-btn-2など)を設定してください。
  • ラベル
    PHPを追加

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

    // フロント用JS・CSSを追加
    add_action('wp_enqueue_scripts', function () {
      $url = admin_url('admin-ajax.php');
      $id  = get_the_ID();
    
      // 既存のクリック数データを取得
      $data   = get_post_meta($id, 'my_download', true);
      $counts = $data ? json_decode($data, true) : [];
    
      ob_start();
      ?>
      jQuery(function ($) {
        // idがmy-btn-で始まる要素を全て取得
        const buttons = $('[id^="my-btn-"]');
    
        // 各ボタンブロックごとに処理
        buttons.each(function () {
          const block = $(this);
          const id = block.attr('id');
    
          if (!id) {
            return;
          }
    
          // 内部のボタン要素と元のテキストを取得
          const btn = block.find('a.btn');
          const originalText = btn.text();
    
          // 既存のカウント値を取得して初期表示に反映
          const count = <?= json_encode($counts); ?>[id] || 0;
          btn.text(originalText + ' ' + count);
    
          // ボタンクリックの場合
          btn.on('click', function (e) {
            e.preventDefault();
    
            $.ajax({
              type: 'POST',
              url: '<?= esc_url($url); ?>',
              dataType: 'json',
              data: {
                action: 'download_counter',
                post_id: <?= (int) $id; ?>,
                button_id: id
              },
              success: function (res) {
                // レスポンスのカウントをボタンに反映
                if (res && res[id] !== undefined) {
                  btn.text(originalText + ' ' + res[id]);
                }
              }
            });
          });
        });
      });
      <?php
      wp_add_inline_script('jquery', ob_get_clean());
    });
    
    
    /**
     * Ajaxコールバック関数
     *
     * @return void
     */
    if (!function_exists('download_counter')):
    function download_counter() {
      $post_id   = (int) $_POST['post_id'];
      $key       = 'my_download';
      $button_id = sanitize_text_field($_POST['button_id']);
    
      $data   = get_post_meta($post_id, $key, true);
      $counts = $data ? json_decode($data, true) : [];
    
      if (!isset($counts[$button_id])) {
        $counts[$button_id] = 0;
      }
    
      $counts[$button_id]++;
    
      update_post_meta($post_id, $key, wp_json_encode($counts));
    
      wp_send_json($counts);
    }
    endif;
    
    
    // Ajaxアクションを追加
    add_action('wp_ajax_download_counter', 'download_counter');
    add_action('wp_ajax_nopriv_download_counter', 'download_counter');

さいごに

今回紹介した方法を使えば、ボタンのクリック数をリアルタイムに反映することができます。
この仕組みは、ダウンロード数やユーザーの行動トラッキングに役立つため、運営効率を高めたい方におすすめです。

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