<?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>slug &#8211; 小豬日常</title>
	<atom:link href="https://piglife.tw/tag/slug/feed/" rel="self" type="application/rss+xml" />
	<link>https://piglife.tw</link>
	<description>Hello World，一個紀錄生活與學習的地方</description>
	<lastBuildDate>Sat, 27 Dec 2025 22:20:37 +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>slug &#8211; 小豬日常</title>
	<link>https://piglife.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>WordPress 自動將文章 slug 設為文章 ID 的實作技巧</title>
		<link>https://piglife.tw/technical-notes/wordpress-post-slug-id/</link>
					<comments>https://piglife.tw/technical-notes/wordpress-post-slug-id/#respond</comments>
		
		<dc:creator><![CDATA[小豬]]></dc:creator>
		<pubDate>Sat, 27 Dec 2025 22:20:37 +0000</pubDate>
				<category><![CDATA[技術筆記]]></category>
		<category><![CDATA[save_post]]></category>
		<category><![CDATA[slug]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[排程文章]]></category>
		<category><![CDATA[文章 ID]]></category>
		<category><![CDATA[網址管理]]></category>
		<guid isPermaLink="false">https://piglife.tw/technical-notes/wordpress-post-slug-id/</guid>

					<description><![CDATA[本文介紹如何在 WordPress 中自動將文章 slug 設為文章 ID，避免重複 slug 並確...]]></description>
										<content:encoded><![CDATA[<h2 class="wp-block-heading">前言</h2>
<p>在 WordPress 中，文章的 slug（網址別名）預設是根據標題自動產生，或由使用者手動設定。有時候為了簡化網址管理或避免重複 slug，會想將 slug 固定為文章的 ID。這段程式碼示範如何在文章發佈或排程時，自動將 slug 設為文章 ID，適合需要統一網址格式的開發者或網站管理者。</p>
<h2 class="wp-block-heading">為什麼要用文章 ID 當 slug？</h2>
<p>文章 ID 是 WordPress 中每篇文章的唯一識別碼，使用 ID 當 slug 可以避免重複 slug 的問題，也方便在程式中直接以 ID 取用文章，提升網址的穩定性與一致性。</p>
<h2 class="wp-block-heading">程式碼解析</h2>
<h3 class="wp-block-heading">1. 使用 save_post Hook</h3>
<p>程式碼利用 WordPress 的 <code>save_post</code> action，這個鉤子會在文章儲存時觸發，能即時修改文章資料。</p>
<pre><code class="lang-php language-php php">add_action(&#039;save_post&#039;, function ($post_id, $post, $update) {
    // 程式內容
}, 20, 3);</code></pre>
<p>這裡設定優先權為 20，並且接受三個參數：文章 ID、文章物件、是否為更新。</p>
<h3 class="wp-block-heading">2. 基本保護條件</h3>
<p>避免對修訂版本（revision）或自動儲存（autosave）執行，減少不必要的處理。</p>
<pre><code class="lang-php language-php php">if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) return;
if (!is_object($post)) return;</code></pre>
<h3 class="wp-block-heading">3. 限制只對文章類型生效</h3>
<p>確保只對 <code>post</code> 文章類型操作，不影響其他自訂文章類型。</p>
<pre><code class="lang-php language-php php">if ($post-&gt;post_type !== &#039;post&#039;) return;</code></pre>
<h3 class="wp-block-heading">4. 限制文章狀態</h3>
<p>只對「已發佈（publish）」與「排程（future）」的文章改寫 slug，避免草稿或其他狀態執行。</p>
<pre><code class="lang-php language-php php">$allowed_status = [&#039;publish&#039;, &#039;future&#039;];
if (!in_array($post-&gt;post_status, $allowed_status, true)) return;</code></pre>
<h3 class="wp-block-heading">5. 判斷是否已是目標 slug</h3>
<p>如果 slug 已經是文章 ID，則不再重寫，避免重複操作。</p>
<pre><code class="lang-php language-php php">$target_slug = (string) $post_id;
if ($post-&gt;post_name === $target_slug) return;</code></pre>
<h3 class="wp-block-heading">6. 防止無限迴圈</h3>
<p><code>wp_update_post</code> 會再次觸發 <code>save_post</code>，容易造成無限迴圈。使用靜態變數 <code>$running</code> 作為旗標，避免重複執行。</p>
<pre><code class="lang-php language-php php">static $running = false;
if ($running) return;
$running = true;</code></pre>
<h3 class="wp-block-heading">7. 更新 slug</h3>
<p>呼叫 <code>wp_update_post</code> 更新文章的 <code>post_name</code> 欄位為文章 ID。</p>
<pre><code class="lang-php language-php php">wp_update_post([
    &#039;ID&#039;        =&gt; $post_id,
    &#039;post_name&#039; =&gt; $target_slug,
]);
$running = false;</code></pre>
<h2 class="wp-block-heading">實務應用與延伸</h2>
<ul>
<li>適合網站需要簡潔、唯一的網址結構，或是避免標題相同導致 slug 重複的情況。</li>
<li>可擴充支援更多文章類型或狀態，只要調整條件判斷即可。</li>
<li>若需保留原本 slug，可改成在自訂欄位或其他欄位存 ID。</li>
<li>注意排程文章的 slug 會在排程時間前就設定完成。</li>
</ul>
<h2 class="wp-block-heading">常見問題與注意事項</h2>
<ul>
<li>無限迴圈問題是此類操作常見的陷阱，務必使用旗標避免。</li>
<li>使用文章 ID 當 slug 可能不利 SEO，需評估是否符合網站策略。</li>
<li>若網站有使用快取或重寫規則，更新 slug 後可能需要清除快取。</li>
</ul>
<h2 class="wp-block-heading">完整程式碼</h2>
<pre><code class="lang-php language-php php">&lt;?php
/**
 * Post 發佈時固定把 slug 設為文章 ID
 * - 只針對 post（文章）
 * - 避免無限迴圈
 * - 若已是 ID slug 就不重寫
 * - 支援 publish / future（排程）/ 更新時維持
 */

add_action(&#039;save_post&#039;, function ($post_id, $post, $update) {

    // 1) 基本保護
    if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) return;
    if (!is_object($post)) return;

    // 2) 只針對文章 post
    if ($post-&gt;post_type !== &#039;post&#039;) return;

    // 3) 只在這些狀態下固定（你也可以只留 publish）
    $allowed_status = [&#039;publish&#039;, &#039;future&#039;]; // future = 排程
    if (!in_array($post-&gt;post_status, $allowed_status, true)) return;

    // 4) 目標 slug = 文章 ID
    $target_slug = (string) $post_id;

    // 5) 已經是目標 slug 就不做事
    if ($post-&gt;post_name === $target_slug) return;

    // 6) 防止 save_post -&gt; wp_update_post -&gt; save_post 無限迴圈
    static $running = false;
    if ($running) return;
    $running = true;

    // 7) 更新 slug
    wp_update_post([
        &#039;ID&#039;        =&gt; $post_id,
        &#039;post_name&#039; =&gt; $target_slug,
    ]);

    $running = false;

}, 20, 3);</code></pre>]]></content:encoded>
					
					<wfw:commentRss>https://piglife.tw/technical-notes/wordpress-post-slug-id/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
