[![WordPress按自定义文章类型进行搜索](https://pic.salongweb.com/2016/07/wordpress-custom-post-type-search.jpg)](https://pic.salongweb.com/2016/07/wordpress-custom-post-type-search.jpg "WordPress按自定义文章类型进行搜索")一般的Wordpress主题中都有多种自定义文章类型，除了了默认的文章还会有作品、商品等自定义类型的文章，而WordPress默认只能搜索到文章，对于自定义文章类型的文章需要我们进行判断，其实也可以在搜索中添加自定义文章类型，但是这些所有的文章类型都在一个页面显示，不好区分。

如果主题中有文章、作品与产品（Woocommerce插件），在搜索中就要对文章类型进行选择，同时搜索结果中显示该文章类型下的文章，实现的方法很简单：

### 为搜索表单添加选项

1、一般的搜索表单：

1. &lt;form method=“get” class=“search-form” action=“&lt;?php echo esc\_url( home\_url( ‘/’ ) ); ?&gt;” &gt;
2. &lt;input class=“search-input” name=“s” type=“text” placeholder=“站内搜索…” /&gt;
3. &lt;input title=“站内搜索” class=“search-submit” type=“submit” value=“”&gt;
4. &lt;/form&gt;

2、添加文章类型选项的表单：

1. &lt;form method=“get” class=“search-form” action=“&lt;?php echo esc\_url( home\_url( ‘/’ ) ); ?&gt;”&gt;
2. &lt;select name=“post\_type” class=“search-select”&gt;
3. &lt;option value=“post”&gt;
4. &lt;?php \_e( ‘文章’, ‘salong’ ); ?&gt;
5. &lt;/option&gt;
6. &lt;option value=“portfolio”&gt;
7. &lt;?php \_e( ‘作品’, ‘salong’ ); ?&gt;
8. &lt;/option&gt;
9. &lt;option value=“product”&gt;
10. &lt;?php \_e( ‘产品’, ‘salong’ ); ?&gt;
11. &lt;/option&gt;
12. &lt;/select&gt;
13. &lt;input class=“search-input” name=“s” type=“text” placeholder=“站内搜索…” /&gt;
14. &lt;input title=“站内搜索” class=“search-submit” type=“submit” value=“”&gt;
15. &lt;/form&gt;

&lt;option value=“post”&gt;中的“post”对应的是自定义文章类型，这样在搜索时就可以选项要搜索的文章类型。表单实现了，搜索结果中得显示对应的内容。

### 对搜索进行判断

1. &lt;?php $post\_type=$\_GET\[‘post\_type’\];
2. $located=get\_template\_part( ‘content/search’, $post\_type );
3. if ( isset( $post\_type ) &amp;&amp; locate\_template($located, $require\_once) ) {
4. get\_template\_part( ‘content/search’, $post\_type );
5. exit;
6. }
7. ?&gt;

注意：“get\_template\_part( ‘content/search’, $post\_type );”是获取主题根目录下的content目录下的search-$post\_type.php文件，如果是文章，文件则为search-post.php，依此类推。

search-$post\_type.php文件中的内容根据主题的情况而定，使用Woocommerce商城插件添加的自定义文章类型产品，不需要添加类似search-product.php文件，因为插件已经有这些文件。