那么,也许在WP_Query
为我想完成的事情上课。下面是我插入函数的最后一段代码。php文件。我最终找到了WP_Query
在中找到类wp_includes/query.php
文件我发现有许多过滤器访问点,可以跳入其中并修改查询。我发现有posts_search
允许我修改发送到数据库的MySQL查询的搜索部分的过滤器。还有一个更具包容性的posts_where
允许我修改更多MySQL查询的过滤器。
感谢Google Groups上的@Scribu over建议对传入查询进行var\\u转储,以查看我使用的过滤器是否允许我访问我想要修改的查询部分。
然而,我最终决定访问全能的posts_request
过滤器,它为我提供了完整的MySQL查询字符串,并允许我提取查询请求的核心,并根据我需要执行的三个不同查询之一进行替换。我修剪了查询的开始和结束并将其存储在变量中,这样就不会破坏查询动态设置的能力。
以下是搜索表单:
function my_search_form( $form ) {
(isset($_REQUEST[\'type\']))? $ic_sType = $_REQUEST[\'type\'] : $ic_sType = \'\';
$ic_selectOpts = array(
\'all\' =>\'General Search [search full site contents]\',
\'name\'=>\'Mineral Name [search the approved name for the mineral]\',
\'detail\'=>\'Description [search the description of the mineral]\',
\'loc\'=>\'Locality [search by mine name, district, state, or country]\'
);
$form = \'<form role="search" method="get" id="top_nav_search" action="\' . home_url( \'/\' ) . \'" >
<div>
<label class="screen-reader-text" for="type">\' . __(\'Type of Search:\') . \'</label>
<select name="type" id="my_search_type" >\';
foreach($my_selectOpts as $myso_key => $myso_val){
$form .= "<option value=\'$myso_key\'";
if($myso_key === $my_sType) $form .= "selected=\'selected\'";
$form .= ">$myso_val</option>";
}
$form .= \'</select>
<label class="screen-reader-text" for="s">\' . __(\'Search Form:\') . \'</label>
<input type="text" value="\' . get_search_query() . \'" name="s" id="s" />
<input type="submit" id="searchsubmit" value="\'. esc_attr__(\'Search\') .\'" />
</div>
</form>\';
return $form;
}
add_filter( \'get_search_form\', \'my_search_form\' );
这是搜索结果过滤器:
function my_search_results($query){
if(isset($_REQUEST[\'type\']) && isset($_REQUEST[\'s\']) && ($_REQUEST[\'type\'] !== \'all\')){
$myType = $_REQUEST[\'type\'];
$mySearch = $_REQUEST[\'s\'];
$qBegin = str_replace(strstr($query, "FROM" ), \'\', $query). \' FROM\';
//echo \'<br>the qBegin string: \'. $qBegin;
$qEnd = strrchr($query, "ORDER BY" );
//echo \'<br>the qEnd string:\' . $qEnd;
switch ($myType){
case \'name\': //Title search
$query = $qBegin. \' wp_posts WHERE 1=1 AND wp_posts.post_title LIKE "%\'.$icSearch.\'%" AND wp_posts.post_type = "mineral" AND (wp_posts.post_password = "") AND(wp_posts.post_status = "publish") \'.$qEnd;
break;
case \'loc\': //Location Search
$query = $qBegin. \' wp_posts,wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND 1=1 AND wp_postmeta.meta_key = "_location_meta" AND wp_postmeta.meta_value LIKE "%\'.$icSearch.\'%" AND wp_posts.post_type = "mineral" AND (wp_posts.post_password = "") AND(wp_posts.post_status = "publish") \'.$qEnd;
break;
case \'detail\': //Details Search
$query = $qBegin. \' wp_posts WHERE 1=1 AND wp_posts.post_content LIKE "%\'.$icSearch.\'%" AND wp_posts.post_type = "mineral" AND (wp_posts.post_password = "") AND(wp_posts.post_status = "publish") \'.$qEnd;
break;
default:
break;
}
}
return $query;
}
add_filter( \'posts_request\', \'my_search_results\');
希望这能帮助其他人。