WordPress按POST_TYPE进行自定义搜索

时间:2011-11-18 作者:php-b-grader

我尝试了几种方法,但我似乎无法从搜索结果中筛选自定义post\\u类型,希望有人能提供帮助。

我安装了“作业管理器”,并创建了4个具有自定义post_type = \'jobman_job\'

我试图创建一个手动搜索表单,并将隐藏值设置为post_type = jobman_job 但它仍然返回了所有帖子。

<form role="search" method="get" id="searchform" action="<?php echo home_url( \'/\' ); ?>">
<input type="text" name="s" id="s" value=""/>
<input type="hidden" name="post_type" value="jobman_job" />
<input type="submit" id="searchsubmit" value="Search" />
</form>
然后,我尝试创建一个自定义搜索页面,并将搜索重定向到此页面,如下所示(即添加了page\\u id隐藏字段):

<form role="search" method="get" id="searchform" action="<?php echo home_url( \'/\' ); ?>">
<input type="text" name="s" id="s" value=""/>
<input type="hidden" name="page_id" value="123" />
<input type="hidden" name="post_type" value="jobman_job" />
<input type="submit" id="searchsubmit" value="Search" />
</form>
然后在自定义搜索页面中,我添加了以下代码(根据wordpress指南-http://codex.wordpress.org/Creating_a_Search_Page) 我将post\\u类型的jobman\\u作业添加到查询数组中:

global $query_string;

$query_args = explode("&", $query_string);
$search_query = array(\'post_type\' => \'jobman_job\');

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach

$search = new WP_Query($search_query);
它仍然显示所有帖子。。。

我做错了什么?我已经检查了wp\\U posts表中的post\\U type列,我有4个唯一的条目。。。所以他们在那里。。。

有什么见解吗?

1 个回复
最合适的回答,由SO网友:andresmijares 整理而成

NOT TESTED!

function mySearchFilter($query) {
$post_type = $_GET[\'type\'];
if (!$post_type) {
    $post_type = \'jobman_job\';
}
if ($query->is_search) {
    $query->set(\'post_type\', $post_type);
};
return $query;
};

 add_filter(\'pre_get_posts\',\'mySearchFilter\');
结束

相关推荐

tag search using WP_Query

我只需要找到带有标签的帖子forest gump. 我尝试过:new WP_Query(\'tag=forest+gump\');, new WP_Query(\'tag=forest gump\');. 然而,他们都会返回所有的帖子,而不仅仅是带有forest gump 标签但是,单个标记(没有空格)可以正常工作。替代方案(如普通SQL)也可以使用。入口标记行为forest gump, forrest gump, questend.