<?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>後台搜尋 &#8211; 小豬日常</title>
	<atom:link href="https://piglife.tw/tag/%e5%be%8c%e5%8f%b0%e6%90%9c%e5%b0%8b/feed/" rel="self" type="application/rss+xml" />
	<link>https://piglife.tw</link>
	<description>Hello World，一個紀錄生活與學習的地方</description>
	<lastBuildDate>Tue, 23 Dec 2025 03:02:20 +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>後台搜尋 &#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-solution-content-search/</link>
					<comments>https://piglife.tw/technical-notes/wordpress-solution-content-search/#respond</comments>
		
		<dc:creator><![CDATA[小豬]]></dc:creator>
		<pubDate>Mon, 22 Dec 2025 22:20:38 +0000</pubDate>
				<category><![CDATA[技術筆記]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[wp_query]]></category>
		<category><![CDATA[內容關鍵字搜尋]]></category>
		<category><![CDATA[後台搜尋]]></category>
		<category><![CDATA[自訂文章類型]]></category>
		<guid isPermaLink="false">https://piglife.tw/technical-notes/wordpress-solution-content-search/</guid>

					<description><![CDATA[介紹如何在 WordPress 自訂文章類型 solution 的後台新增內容關鍵字搜尋功能，透過 ...]]></description>
										<content:encoded><![CDATA[<h2 class="wp-block-heading">前言</h2>
<p>在 WordPress 後台管理自訂文章類型（此處為 solution）時，若想快速搜尋文章內容中是否包含特定關鍵字，系統預設的搜尋功能可能無法精準或方便達成此需求。這段程式碼示範如何為 solution 文章類型新增一個後台子選單，提供內容關鍵字搜尋功能，適合需要管理大量文章並快速定位內容的開發者與網站管理員。</p>
<h2 class="wp-block-heading">新增後台子選單</h2>
<p>使用 <code>admin_menu</code> action，先檢查 solution 文章類型是否存在，避免錯誤。接著透過 <code>add_submenu_page</code> 在 solution 列表底下新增「內容關鍵字搜尋」子選單，設定權限為 <code>edit_posts</code>，確保只有具備編輯權限的使用者能操作。</p>
<pre><code class="lang-php language-php php">add_action( &#039;admin_menu&#039;, function () {
    if ( ! post_type_exists( &#039;solution&#039; ) ) {
        return;
    }

    add_submenu_page(
        &#039;edit.php?post_type=solution&#039;,
        &#039;內容關鍵字搜尋&#039;,
        &#039;內容關鍵字搜尋&#039;,
        &#039;edit_posts&#039;,
        &#039;solution-content-search&#039;,
        &#039;solution_content_search_page_render&#039;
    );
} );</code></pre>
<h2 class="wp-block-heading">搜尋頁面渲染與表單處理</h2>
<p><code>solution_content_search_page_render</code> 函式負責渲染搜尋表單與結果頁面。首先檢查使用者權限，避免未授權存取。接著判斷是否有表單送出，並使用 WordPress 的 nonce 機制驗證安全性。</p>
<p>關鍵字透過 <code>sanitize_text_field</code> 與 <code>wp_unslash</code> 清理，避免 XSS 與注入風險。</p>
<pre><code class="lang-php language-php php">if ( isset( $_POST[&#039;solution_content_search_submit&#039;] ) ) {
    check_admin_referer( &#039;solution_content_search_action&#039;, &#039;solution_content_search_nonce&#039; );

    $keyword  = isset( $_POST[&#039;solution_keyword&#039;] ) ? sanitize_text_field( wp_unslash( $_POST[&#039;solution_keyword&#039;] ) ) : &#039;&#039;;
    $searched = true;

    if ( $keyword !== &#039;&#039; ) {
        // ...
    }
}</code></pre>
<h2 class="wp-block-heading">透過 WP_Query 及字串比對精確搜尋</h2>
<p>WordPress 內建搜尋（<code>s</code> 參數）會搜尋標題、內容等欄位，但可能不夠精準。此處先用 <code>WP_Query</code> 以關鍵字搜尋取得可能相關文章 ID，然後逐篇讀取內容，使用 <code>mb_stripos</code>（若有）或 <code>stripos</code> 做不區分大小寫的字串比對，確保內容確實包含關鍵字。</p>
<pre><code class="lang-php language-php php">$query = new WP_Query( array(
    &#039;post_type&#039;      =&gt; &#039;solution&#039;,
    &#039;post_status&#039;    =&gt; &#039;any&#039;,
    &#039;posts_per_page&#039; =&gt; -1,
    &#039;s&#039;              =&gt; $keyword,
    &#039;fields&#039;         =&gt; &#039;ids&#039;,
) );

foreach ( $query-&gt;posts as $post_id ) {
    $post = get_post( $post_id );
    if ( ! $post ) {
        continue;
    }

    $content = wp_strip_all_tags( $post-&gt;post_content );

    if ( function_exists( &#039;mb_stripos&#039; ) ) {
        $pos = mb_stripos( $content, $keyword );
    } else {
        $pos = stripos( $content, $keyword );
    }

    if ( $pos !== false ) {
        $results[] = $post_id;
    }
}
wp_reset_postdata();</code></pre>
<h2 class="wp-block-heading">搜尋結果呈現與操作介面</h2>
<p>搜尋結果會以表格形式呈現，包含文章 ID、標題（連結至編輯頁面）、前台連結與編輯按鈕，方便快速查看與編輯。若無輸入關鍵字或找不到結果，會顯示相應提示訊息。</p>
<p>表單使用 WordPress 內建的 <code>wp_nonce_field</code> 與 <code>submit_button</code>，確保安全與一致性。</p>
<h2 class="wp-block-heading">實務應用與優化方向</h2>
<p>此搜尋功能適合用於自訂文章類型管理，尤其是內容量大且需要精準定位文本的場景。未來可考慮加入分頁功能避免一次載入過多文章，或結合全文索引外掛提升搜尋效能。也可擴充搜尋範圍至自訂欄位或分類。</p>
<h2 class="wp-block-heading">完整程式碼</h2>
<pre><code class="lang-php language-php php">&lt;?php
// 在「solution」這個 post type 底下新增一個後台子選單：內容關鍵字搜尋
add_action( &#039;admin_menu&#039;, function () {
    // 確保有這個 post type
    if ( ! post_type_exists( &#039;solution&#039; ) ) {
        return;
    }

    add_submenu_page(
        &#039;edit.php?post_type=solution&#039;,          // 父層 (solution 列表底下)
        &#039;內容關鍵字搜尋&#039;,                        // 頁面標題
        &#039;內容關鍵字搜尋&#039;,                        // 左側選單名稱
        &#039;edit_posts&#039;,                           // 權限
        &#039;solution-content-search&#039;,              // slug
        &#039;solution_content_search_page_render&#039;   // callback
    );
} );

// 後台頁面：渲染搜尋表單與結果
function solution_content_search_page_render() {
    if ( ! current_user_can( &#039;edit_posts&#039; ) ) {
        wp_die( &#039;沒有權限檢視此頁面。&#039; );
    }

    $keyword  = &#039;&#039;;
    $results  = array();
    $searched = false;

    // 處理表單送出
    if ( isset( $_POST[&#039;solution_content_search_submit&#039;] ) ) {
        check_admin_referer( &#039;solution_content_search_action&#039;, &#039;solution_content_search_nonce&#039; );

        $keyword  = isset( $_POST[&#039;solution_keyword&#039;] ) ? sanitize_text_field( wp_unslash( $_POST[&#039;solution_keyword&#039;] ) ) : &#039;&#039;;
        $searched = true;

        if ( $keyword !== &#039;&#039; ) {
            // 先用 WP_Query 找出可能包含關鍵字的文章 (全文搜尋)
            $query = new WP_Query( array(
                &#039;post_type&#039;      =&gt; &#039;solution&#039;,
                &#039;post_status&#039;    =&gt; &#039;any&#039;,
                &#039;posts_per_page&#039; =&gt; -1,
                &#039;s&#039;              =&gt; $keyword,
                &#039;fields&#039;         =&gt; &#039;ids&#039;,
            ) );

            if ( $query-&gt;have_posts() ) {
                foreach ( $query-&gt;posts as $post_id ) {
                    $post = get_post( $post_id );
                    if ( ! $post ) {
                        continue;
                    }

                    // 從內容中做字串檢查（確保 content 真的有包含關鍵字）
                    $content = wp_strip_all_tags( $post-&gt;post_content );

                    if ( function_exists( &#039;mb_stripos&#039; ) ) {
                        $pos = mb_stripos( $content, $keyword );
                    } else {
                        $pos = stripos( $content, $keyword );
                    }

                    if ( $pos !== false ) {
                        $results[] = $post_id;
                    }
                }
            }
            wp_reset_postdata();
        }
    }

    ?&gt;
    &lt;div class=&quot;wrap&quot;&gt;

&lt;h1&gt;Solution 內容關鍵字搜尋&lt;/h1&gt;

&lt;p&gt;輸入一個關鍵字，系統會掃描 &amp;lt;code&amp;gt;solution&amp;lt;/code&amp;gt;
 文章類型的內容（content），只要有包含該字串，就列出標題與編輯連結。&lt;/p&gt;

        &lt;form method=&quot;post&quot; style=&quot;margin-top: 1em; margin-bottom: 2em;&quot;&gt;
            &lt;?php wp_nonce_field( &#039;solution_content_search_action&#039;, &#039;solution_content_search_nonce&#039; ); ?&gt;

            &lt;table class=&quot;form-table&quot; role=&quot;presentation&quot;&gt;

&lt;tr&gt;
                    &lt;th scope=&quot;row&quot;&gt;
                        &lt;label for=&quot;solution_keyword&quot;&gt;關鍵字字串&lt;/label&gt;
                    &lt;/th&gt;

&lt;td&gt;
                        &lt;input
                            type=&quot;text&quot;
                            id=&quot;solution_keyword&quot;
                            name=&quot;solution_keyword&quot;
                            class=&quot;regular-text&quot;
                            value=&quot;&lt;?php echo esc_attr( $keyword ); ?&gt;&quot;
                            placeholder=&quot;例如：API、某段程式碼、特定中文句子&quot;
                        /&gt;
                    &lt;/td&gt;
                &lt;/tr&gt;
            &lt;/table&gt;

            &lt;?php submit_button( &#039;開始搜尋&#039;, &#039;primary&#039;, &#039;solution_content_search_submit&#039; ); ?&gt;
        &lt;/form&gt;

        &lt;?php if ( $searched ) : ?&gt;

&lt;h2&gt;搜尋結果&lt;/h2&gt;

            &lt;?php if ( $keyword === &#039;&#039; ) : ?&gt;
                &lt;div class=&quot;notice notice-warning&quot;&gt;&lt;p&gt;請輸入關鍵字。&lt;/p&gt;&lt;/div&gt;
            &lt;?php elseif ( empty( $results ) ) : ?&gt;
                &lt;div class=&quot;notice notice-info&quot;&gt;&lt;p&gt;沒有找到內容包含「&lt;?php echo esc_html( $keyword ); ?&gt;」的 solution 文章。&lt;/p&gt;&lt;/div&gt;
            &lt;?php else : ?&gt;

&lt;p&gt;找到 &lt;?php echo esc_html( count( $results ) ); ?&gt; 篇文章，內容中包含「&lt;?php echo esc_html( $keyword ); ?&gt;」。&lt;/p&gt;

                &lt;table class=&quot;widefat fixed striped&quot;&gt;

&lt;thead&gt;

&lt;tr&gt;
                            &lt;th scope=&quot;col&quot; style=&quot;width: 50px;&quot;&gt;ID&lt;/th&gt;
                            &lt;th scope=&quot;col&quot;&gt;標題&lt;/th&gt;
                            &lt;th scope=&quot;col&quot; style=&quot;width: 200px;&quot;&gt;前台連結&lt;/th&gt;
                            &lt;th scope=&quot;col&quot; style=&quot;width: 150px;&quot;&gt;編輯&lt;/th&gt;
                        &lt;/tr&gt;
                    &lt;/thead&gt;

&lt;tbody&gt;
                    &lt;?php foreach ( $results as $post_id ) :
                        $title     = get_the_title( $post_id );
                        $view_link = get_permalink( $post_id );
                        $edit_link = get_edit_post_link( $post_id, &#039;&#039; );
                    ?&gt;

&lt;tr&gt;

&lt;td&gt;&lt;?php echo esc_html( $post_id ); ?&gt;&lt;/td&gt;

&lt;td&gt;
                                &lt;?php if ( $edit_link ) : ?&gt;
                                    &lt;a href=&quot;&lt;?php echo esc_url( $edit_link ); ?&gt;&quot;&gt;
                                        &lt;?php echo esc_html( $title ); ?&gt;
                                    &lt;/a&gt;
                                &lt;?php else : ?&gt;
                                    &lt;?php echo esc_html( $title ); ?&gt;
                                &lt;?php endif; ?&gt;
                            &lt;/td&gt;

&lt;td&gt;
                                &lt;?php if ( $view_link ) : ?&gt;
                                    &lt;a href=&quot;&lt;?php echo esc_url( $view_link ); ?&gt;&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;
                                        檢視
                                    &lt;/a&gt;
                                &lt;?php else : ?&gt;
                                    -
                                &lt;?php endif; ?&gt;
                            &lt;/td&gt;

&lt;td&gt;
                                &lt;?php if ( $edit_link ) : ?&gt;
                                    &lt;a href=&quot;&lt;?php echo esc_url( $edit_link ); ?&gt;&quot; class=&quot;button button-small&quot;&gt;
                                        編輯文章
                                    &lt;/a&gt;
                                &lt;?php else : ?&gt;
                                    -
                                &lt;?php endif; ?&gt;
                            &lt;/td&gt;
                        &lt;/tr&gt;
                    &lt;?php endforeach; ?&gt;
                    &lt;/tbody&gt;
                &lt;/table&gt;
            &lt;?php endif; ?&gt;
        &lt;?php endif; ?&gt;
    &lt;/div&gt;
    &lt;?php
}</code></pre>]]></content:encoded>
					
					<wfw:commentRss>https://piglife.tw/technical-notes/wordpress-solution-content-search/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
