<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>cookie &#8211; 小豬日常</title>
	<atom:link href="https://piglife.tw/tag/cookie/feed/" rel="self" type="application/rss+xml" />
	<link>https://piglife.tw</link>
	<description>Hello World，一個紀錄生活與學習的地方</description>
	<lastBuildDate>Fri, 12 Dec 2025 14:48:11 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://piglife.tw/wp-content/uploads/2017/10/cropped-logo-1-32x32.png</url>
	<title>cookie &#8211; 小豬日常</title>
	<link>https://piglife.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>WordPress 實作瀏覽器語言自動轉址功能筆記</title>
		<link>https://piglife.tw/technical-notes/wordpress-browser-language-redirect/</link>
					<comments>https://piglife.tw/technical-notes/wordpress-browser-language-redirect/#respond</comments>
		
		<dc:creator><![CDATA[小豬]]></dc:creator>
		<pubDate>Tue, 31 Dec 2024 02:39:25 +0000</pubDate>
				<category><![CDATA[技術筆記]]></category>
		<category><![CDATA[cookie]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[前端]]></category>
		<category><![CDATA[多國語系]]></category>
		<category><![CDATA[瀏覽器語言]]></category>
		<category><![CDATA[自動轉址]]></category>
		<guid isPermaLink="false">https://piglife.tw/?p=435</guid>

					<description><![CDATA[介紹如何在 WordPress 網站中利用 JavaScript 根據瀏覽器語言自動轉址至指定語言頁...]]></description>
										<content:encoded><![CDATA[<h2 class="wp-block-heading">前言</h2>
<p>在多國語系網站中，根據用戶瀏覽器語言自動轉址至對應語言頁面是提升用戶體驗的常見需求。本文適合具備基礎程式能力的工程師或自學者，說明如何利用 JavaScript 搭配 Cookie 控制，實現 WordPress 網站的語言自動轉址功能。</p>
<h2 class="wp-block-heading">教學步驟</h2>
<h3 class="wp-block-heading">1. JavaScript 程式碼說明</h3>
<p>將以下程式碼加入 WordPress 主題的 <code>wp_footer</code> 或 JavaScript 檔案中，確保頁面載入時執行：</p>
<pre><code class="lang-javascript language-javascript javascript">document.addEventListener(&quot;DOMContentLoaded&quot;, function () {
  // 設置 Cookie
  function setCookie(name, value, days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = &quot;expires=&quot; + date.toUTCString();
    document.cookie = name + &quot;=&quot; + value + &quot;;&quot; + expires + &quot;;path=/&quot;;
  }

  // 取得 Cookie
  function getCookie(name) {
    const nameEQ = name + &quot;=&quot;;
    const ca = document.cookie.split(&#039;;&#039;);
    for (let i = 0; i &lt; ca.length; i++) {
      let c = ca[i].trim();
      if (c.indexOf(nameEQ) === 0) {
        return c.substring(nameEQ.length, c.length);
      }
    }
    return null;
  }

  // 僅在首頁執行
  if (window.location.pathname === &#039;/&#039;) {
    if (!getCookie(&#039;redirected&#039;)) {
      const browserLanguage = navigator.language || navigator.userLanguage;
      // 繁體中文判斷
      if (browserLanguage.startsWith(&#039;zh&#039;) &amp;&amp; window.location.pathname !== &#039;/zh-tw/&#039;) {
        setCookie(&#039;redirected&#039;, &#039;true&#039;, 1); // 設置 1 天有效期
        window.location.href = &#039;https://xxxxx.com/zh-tw/&#039;;
      }
    }
  }
});</code></pre>
<h3 class="wp-block-heading">2. 功能解析</h3>
<ul>
<li><strong>Cookie 操作函數</strong>：<code>setCookie</code> 用於建立帶有效期的 Cookie，<code>getCookie</code> 用於檢查 Cookie 是否存在。</li>
<li><strong>語言判斷與轉址</strong>：透過 <code>navigator.language</code> 取得瀏覽器語言，判斷是否為繁體中文（<code>zh-TW</code> 或 <code>zh-HK</code>），並且當前不在繁體中文頁面時執行轉址。</li>
<li><strong>避免重複轉址</strong>：利用名為 <code>redirected</code> 的 Cookie 記錄轉址狀態，避免用戶在有效期內重複被轉址。</li>
</ul>
<h3 class="wp-block-heading">3. 使用方法</h3>
<ul>
<li>將程式碼加入 WordPress 主題或插件中，確保在頁面載入時執行。</li>
<li>測試時可透過瀏覽器語言設定模擬不同語言環境，確認轉址是否正常。</li>
<li>使用瀏覽器開發者工具檢查 <code>redirected</code> Cookie 是否正確設置，確保轉址邏輯生效且不重複。</li>
</ul>
<h3 class="wp-block-heading">4. 注意事項</h3>
<ul>
<li>本程式碼僅在首頁生效，如需其他頁面轉址，需擴充路徑判斷邏輯。</li>
<li>Cookie 有效期可依需求調整。</li>
<li>可擴展語言判斷條件，支持更多語言轉址。</li>
<li>注意 SEO 影響，避免搜尋引擎因轉址影響索引。</li>
</ul>
<h3 class="wp-block-heading">範例應用場景</h3>
<p>假設網站有英文首頁 <code>https://xxxxx.com/</code> 與繁體中文頁面 <code>https://xxxxx.com/zh-tw/</code>，當用戶瀏覽器語言為繁體中文時，會自動導向繁體中文頁面，提升使用者體驗與網站國際化支持。</p>
<h2 class="wp-block-heading">完整程式碼</h2>
<pre><code class="lang-text language-text text">document.addEventListener(&quot;DOMContentLoaded&quot;, function () {
  // 設置 Cookie 的函數
  function setCookie(name, value, days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = &quot;expires=&quot; + date.toUTCString();
    document.cookie = name + &quot;=&quot; + value + &quot;;&quot; + expires + &quot;;path=/&quot;;
  }

  // 獲取 Cookie 的函數
  function getCookie(name) {
    const nameEQ = name + &quot;=&quot;;
    const ca = document.cookie.split(&#039;;&#039;);
    for (let i = 0; i &lt; ca.length; i++) {
      let c = ca[i].trim();
      if (c.indexOf(nameEQ) === 0) {
        return c.substring(nameEQ.length, c.length);
      }
    }
    return null;
  }

  // 確保僅在首頁執行
  if (window.location.pathname === &#039;/&#039;) {
    // 檢查是否已設置轉址 Cookie
    if (!getCookie(&#039;redirected&#039;)) {
      // 獲取瀏覽器語言
      const browserLanguage = navigator.language || navigator.userLanguage;

      // 判斷是否為繁體中文 (zh-TW 或 zh-HK)
      if (browserLanguage.startsWith(&#039;zh&#039;) &amp;&amp; window.location.pathname !== &#039;/zh-tw/&#039;) {
        // 設置轉址 Cookie，有效期為 1 天
        setCookie(&#039;redirected&#039;, &#039;true&#039;, 1);

        // 執行轉址
        window.location.href = &#039;https://xxxxx.com/zh-tw/&#039;;
      }
    }
  }
});</code></pre>]]></content:encoded>
					
					<wfw:commentRss>https://piglife.tw/technical-notes/wordpress-browser-language-redirect/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>WordPress 實作 UTM 參數自動追蹤功能筆記</title>
		<link>https://piglife.tw/technical-notes/wordpress-utm-parameter-tracking/</link>
					<comments>https://piglife.tw/technical-notes/wordpress-utm-parameter-tracking/#respond</comments>
		
		<dc:creator><![CDATA[小豬]]></dc:creator>
		<pubDate>Fri, 27 Dec 2024 02:43:04 +0000</pubDate>
				<category><![CDATA[技術筆記]]></category>
		<category><![CDATA[cookie]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[utm參數]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[流量追蹤]]></category>
		<category><![CDATA[網址參數]]></category>
		<guid isPermaLink="false">https://piglife.tw/?p=426</guid>

					<description><![CDATA[介紹如何在 WordPress 中利用 PHP 與 JavaScript 自動儲存並補充 UTM 參...]]></description>
										<content:encoded><![CDATA[<h2 class="wp-block-heading">前言</h2>
<p>在行銷活動中，UTM 參數（如 utm_source、utm_medium、utm_campaign）是分析流量來源的重要依據。但當訪客瀏覽網站內頁時，這些參數往往會遺失，導致追蹤不完整。本文針對 WordPress 平台，介紹如何利用 PHP 與 JavaScript，實現 UTM 參數的自動儲存與補充，確保參數在整個瀏覽過程中不會消失。</p>
<h2 class="wp-block-heading">儲存 UTM 參數到 Cookie</h2>
<p>在 WordPress 主題的 <code>functions.php</code> 中，我們透過 <code>init</code> 鉤子檢查 URL 是否帶有 UTM 參數，若有則將其經過安全處理後存入 Cookie，並設定有效期限為 30 天。關鍵程式碼如下：</p>
<pre><code class="lang-php language-php php">function ks_store_utm_in_cookie() {
 if (isset($_GET[&#039;utm_source&#039;]) || isset($_GET[&#039;utm_medium&#039;]) || isset($_GET[&#039;utm_campaign&#039;])) {
 $utm_data = array_filter([
 &#039;utm_source&#039; =&gt; isset($_GET[&#039;utm_source&#039;]) ? sanitize_text_field($_GET[&#039;utm_source&#039;]) : &#039;&#039;,
 &#039;utm_medium&#039; =&gt; isset($_GET[&#039;utm_medium&#039;]) ? sanitize_text_field($_GET[&#039;utm_medium&#039;]) : &#039;&#039;,
 &#039;utm_campaign&#039; =&gt; isset($_GET[&#039;utm_campaign&#039;]) ? sanitize_text_field($_GET[&#039;utm_campaign&#039;]) : &#039;&#039;,
 ]);

 // 儲存 UTM 到 Cookie
 setcookie(&#039;utm_data&#039;, json_encode($utm_data), time() + (30 * DAY_IN_SECONDS), &#039;/&#039;);
 }
}
add_action(&#039;init&#039;, &#039;ks_store_utm_in_cookie&#039;);</code></pre>
<h2 class="wp-block-heading">動態補充 UTM 參數到當前網址</h2>
<p>為了避免使用者在瀏覽其他頁面時丟失 UTM 參數，我們在頁面底部（<code>wp_footer</code>）注入 JavaScript。此腳本會讀取 Cookie 中的 UTM 資料，並判斷當前網址是否缺少 <code>utm_source</code>，若缺少則動態將參數附加到網址，且不刷新頁面。核心程式碼片段：</p>
<pre><code class="lang-php language-php php">function ks_add_utm_to_current_url() {
 ?&gt;
 &lt;script&gt;
 document.addEventListener(&quot;DOMContentLoaded&quot;, function () {
 const utmData = getCookie(&#039;utm_data&#039;);
 if (utmData) {
 const utmParams = JSON.parse(utmData);
 const queryString = Object.entries(utmParams).map(([key, value]) =&gt; `${key}=${encodeURIComponent(value)}`).join(&#039;&amp;&#039;);

 const currentUrl = new URL(window.location.href);

 // 如果網址中沒有 utm_source，補充 UTM 參數
 if (!currentUrl.searchParams.has(&#039;utm_source&#039;) &amp;&amp; queryString) {
 currentUrl.search = currentUrl.search ? `${currentUrl.search}&amp;${queryString}` : `?${queryString}`;
 window.history.replaceState(null, &#039;&#039;, currentUrl.toString());
 }
 }

 // 取得 Cookie 值的函數
 function getCookie(name) {
 const match = document.cookie.match(new RegExp(&#039;(^| )&#039; + name + &#039;=([^;]+)&#039;));
 if (match) return decodeURIComponent(match[2]);
 return null;
 }
 });
 &lt;/script&gt;
 &lt;?php
}
add_action(&#039;wp_footer&#039;, &#039;ks_add_utm_to_current_url&#039;);</code></pre>
<h2 class="wp-block-heading">功能解析</h2>
<ul>
<li><strong>PHP 部分</strong>：
<ul>
<li>偵測 URL 中的 UTM 參數並存入 Cookie，確保 30 天內可持續追蹤。</li>
</ul></li>
<li><strong>JavaScript 部分</strong>：
<ul>
<li>從 Cookie 讀取 UTM 資料。</li>
<li>若當前網址缺少 UTM 參數，動態補充並更新網址，不刷新頁面。</li>
</ul></li>
</ul>
<h2 class="wp-block-heading">使用方法</h2>
<ol>
<li>編輯 WordPress 主題的 <code>functions.php</code>，貼入上述 PHP 與 JavaScript 程式碼。</li>
<li>在瀏覽器中輸入帶有 UTM 參數的網址，例如：
<code>https://example.com/?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=winter-sale</code></li>
<li>確認瀏覽其他頁面時，網址仍保有 UTM 參數。</li>
<li>使用瀏覽器開發者工具檢查 Cookie，確認 <code>utm_data</code> 已成功儲存。</li>
</ol>
<h2 class="wp-block-heading">注意事項</h2>
<ul>
<li>確保網站啟用 JavaScript，否則動態補充功能無法運作。</li>
<li>若使用 CDN 或快取插件，請測試是否影響此功能。</li>
</ul>
<h2 class="wp-block-heading">完整程式碼</h2>
<pre><code class="lang-text language-text text">&lt;?php
// 儲存 UTM 參數到 Cookie
function ks_store_utm_in_cookie() {
 if (isset($_GET[&#039;utm_source&#039;]) || isset($_GET[&#039;utm_medium&#039;]) || isset($_GET[&#039;utm_campaign&#039;])) {
 $utm_data = array_filter([
 &#039;utm_source&#039; =&gt; isset($_GET[&#039;utm_source&#039;]) ? sanitize_text_field($_GET[&#039;utm_source&#039;]) : &#039;&#039;,
 &#039;utm_medium&#039; =&gt; isset($_GET[&#039;utm_medium&#039;]) ? sanitize_text_field($_GET[&#039;utm_medium&#039;]) : &#039;&#039;,
 &#039;utm_campaign&#039; =&gt; isset($_GET[&#039;utm_campaign&#039;]) ? sanitize_text_field($_GET[&#039;utm_campaign&#039;]) : &#039;&#039;,
 ]);

 setcookie(&#039;utm_data&#039;, json_encode($utm_data), time() + (30 * DAY_IN_SECONDS), &#039;/&#039;);
 }
}
add_action(&#039;init&#039;, &#039;ks_store_utm_in_cookie&#039;);

// 動態補充 UTM 參數到當前網址
function ks_add_utm_to_current_url() {
 ?&gt;
 &lt;script&gt;
 document.addEventListener(&quot;DOMContentLoaded&quot;, function () {
 const utmData = getCookie(&#039;utm_data&#039;);
 if (utmData) {
 const utmParams = JSON.parse(utmData);
 const queryString = Object.entries(utmParams).map(([key, value]) =&gt; `${key}=${encodeURIComponent(value)}`).join(&#039;&amp;&#039;);

 const currentUrl = new URL(window.location.href);

 if (!currentUrl.searchParams.has(&#039;utm_source&#039;) &amp;&amp; queryString) {
 currentUrl.search = currentUrl.search ? `${currentUrl.search}&amp;${queryString}` : `?${queryString}`;
 window.history.replaceState(null, &#039;&#039;, currentUrl.toString());
 }
 }

 function getCookie(name) {
 const match = document.cookie.match(new RegExp(&#039;(^| )&#039; + name + &#039;=([^;]+)&#039;));
 if (match) return decodeURIComponent(match[2]);
 return null;
 }
 });
 &lt;/script&gt;
 &lt;?php
}
add_action(&#039;wp_footer&#039;, &#039;ks_add_utm_to_current_url&#039;);
?&gt;</code></pre>]]></content:encoded>
					
					<wfw:commentRss>https://piglife.tw/technical-notes/wordpress-utm-parameter-tracking/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
