1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WordPress記事別効果測定用パラメータ付与自動化

Last updated at Posted at 2025-07-19

概要

WordPressサイトから外部LPへの流入を記事単位で追跡する為に、記事内のリンクに動的にUTMパラメータを付与し、Google AnalyticsやSegmetrics等の解析ツールで詳細な効果測定を容易にします

主要コード全体像

slug.js
window.addEventListener('DOMContentLoaded', function() {
  // 対象LPドメイン
  const lpDomain = 'hiltltraining.com';

  // 現在のページのスラッグ(末尾部分だけを抽出)
  const urlSegments = window.location.pathname.split('/').filter(Boolean);
  const slug = urlSegments.length > 0 ? urlSegments[urlSegments.length - 1] : 'home';

  // 全aタグ
  document.querySelectorAll('a[href^="http"]').forEach(link => {
    try {
      const url = new URL(link.href);

      // 対象リンク
      if (url.hostname.includes(lpDomain) && !url.searchParams.has('utm_content')) {
        // 既存パラメータに追加
        url.searchParams.set('utm_source', 'officialsite');
        url.searchParams.set('utm_content', slug);
        link.href = url.toString();
      }
    } catch (e) {
      // エラーログ用
      fetch('/log.php', {
        method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		  body: JSON.stringify({
		  type: 'link_parse_error',
		  href: link.href,
		  message: e.message,
    	  stack: e.stack
		});
	  });
	};
  });
});

システム構成

1. JavaScript側の実装

ページスラッグの動的取得:

slug.js
javascriptconst urlSegments = window.location.pathname.split('/').filter(Boolean);
const slug = urlSegments.length > 0 ? urlSegments[urlSegments.length - 1] : 'home';
  • window.location.pathnameからURLパスを取得
  • /で分割し、filter(Boolean)で空文字列を除去
  • 配列の最後の要素を記事スラッグとして使用
  • フォールバック値として'home'を設定

例:

/blog/seo-optimization/ → slug = 'seo-optimization'
/category/news/latest-update/ → slug = 'latest-update'

外部リンクの動的パラメータ付与:

slug.js
javascriptdocument.querySelectorAll('a[href^="http"]').forEach(link => {
  try {
    const url = new URL(link.href);
    if (url.hostname.includes(lpDomain) && !url.searchParams.has('utm_content')) {
      url.searchParams.set('utm_source', 'officialsite'); //固定値
      url.searchParams.set('utm_content', slug); //動的に取得したスラッグ
      link.href = url.toString();
    }
  } catch (e) {
    // エラーハンドリング
  }
});
  1. a[href^="http"]セレクタで絶対URLのリンクのみを対象
  2. url.hostname.includes(lpDomain)で対象ドメインをチェック
  3. !url.searchParams.has('utm_content')で既存パラメータ重複を回避
  4. パラメータ付与
    utm_source: 'officialsite'(固定値)
    utm_content: 動的に取得したスラッグ

エラーハンドリングとログ収集:

slug.js
javascriptcatch (e) {
  fetch('/log.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      type: 'link_parse_error',
      href: link.href,
      message: e.message,
      stack: e.stack
    })
  });
}

2. WordPress側の実装

条件付きスクリプト読み込み:

functios.php
function add_slug() {
  if (is_single() && 'post' === get_post_type()) {
    wp_enqueue_script(
      'slug-script',
      get_stylesheet_directory_uri() . '/sys/projects/wp/blog/slug.js',
      [],
      null,
      true
    );
  }
}
add_action('wp_enqueue_scripts', 'add_slug');
  • パフォーマンス最適化:is_single() && 'post' === get_post_type()で投稿記事のみに限定し不要なページでのスクリプト読み込み回避
  • 第5引数trueでbody終了タグ前に配置

UTMパラメータ設計:

元URL:https://hiltltraining.com/course
変換後(例):https://hiltltraining.com/course?utm_source=officialsite&utm_content=seo-optimization

utm_source:流入元(ヒルトルフィリップ太郎公式サイト
utm_content:記事スラッグ(記事の識別)

これで記事作成時に手動でパラメータを設定する必要がなくなり、既存記事の一括適用が可能になりました!

まとめ

このシステムでは、WordPress記事の効果測定において手動作業を排除し、JavaScriptを使ったブラウザ上でのリアルタイム処理によって既存記事への遡及適用や環境に応じた動的対応、またWordPressのAPIを活用した精密なページ判定でパフォーマンス最適化を実現しました

これによる解析データの精度向上で、コンテンツマーケティングのROI測定とPDCAサイクルの高速化が期待出来ます

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?