モバイル端末で左右スワイプして前後の記事へページ遷移する方法

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

はじめに

投稿ページで、スマートフォンの画面を左右にスワイプして前後の投稿へ移動できるようにします。
ページ送りボタン操作ではなく、タッチ操作を検知して通常のページ遷移を行います。

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

実装手順

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

add_action('wp_enqueue_scripts', function () {
  // 投稿ページかつモバイル以外は処理対象外
  if (!is_single() || !wp_is_mobile()) {
    return;
  }

  // ページ送りナビが非表示の場合は処理対象外
  if (!is_post_navi_visible()) {
    return;
  }

  // ページ送り設定を取得
  $in_same_term = is_post_navi_same_category_enable();
  $excluded_terms = sanitize_array(get_post_navi_exclude_category_ids());

  // タクソノミーを取得
  $taxonomy = 'category';
  $post_type = get_post_type();
  if ($post_type) {
    $taxonomies = get_object_taxonomies($post_type);
    if ($taxonomies && isset($taxonomies[0])) {
      $taxonomy = $taxonomies[0];
    }
  }

  // タクソノミーを変更
  $taxonomy = apply_filters('post_navi_taxonomy', $taxonomy);

  // 前後の記事を取得
  $prev = get_adjacent_post($in_same_term, $excluded_terms, true, $taxonomy);
  $next = get_adjacent_post($in_same_term, $excluded_terms, false, $taxonomy);

  // 前後の記事のURLを取得
  $prev_url = $prev ? get_permalink($prev->ID) : '';
  $next_url = $next ? get_permalink($next->ID) : '';

  // 前後の記事がない場合は処理対象外
  if (!$prev_url && !$next_url) {
    return;
  }

  ob_start();
  ?>
  jQuery(function ($) {
    // スワイプ開始位置を設定
    let startX = 0;
    let startY = 0;

    // タッチ開始時の座標を取得
    $(document).on('touchstart', function (e) {
      startX = e.originalEvent.touches[0].clientX;
      startY = e.originalEvent.touches[0].clientY;
    });

    // タッチ終了時の座標を取得
    $(document).on('touchend', function (e) {
      const endX = e.originalEvent.changedTouches[0].clientX;
      const endY = e.originalEvent.changedTouches[0].clientY;

      // 移動距離を取得
      const diffX = endX - startX;
      const diffY = endY - startY;

      // 横移動が80px未満、または縦移動が大きい場合は処理対象外
      if (Math.abs(diffX) < 80 || Math.abs(diffX) <= Math.abs(diffY)) {
        return;
      }

      // 左スワイプで次の記事へ移動
      if (diffX < 0 && <?= $next_url ? 'true' : 'false'; ?>) {
        location.href = <?= wp_json_encode($next_url); ?>;

      // 右スワイプで前の記事へ移動
      } else if (diffX > 0 && <?= $prev_url ? 'true' : 'false'; ?>) {
        location.href = <?= wp_json_encode($prev_url); ?>;
      }
    });
  });
  <?php
  wp_add_inline_script('jquery', ob_get_clean());
});

さいごに

今回紹介した方法を使えば、スマートフォンでの閲覧時に直感的な左右スワイプ操作で前後の投稿へスムーズにページ遷移できるようになります。
ページネーションボタンをタップする手間を省くことでユーザーの回遊率や滞在時間の向上が期待できますので、ぜひサイトの利便性向上にお役立てください。

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