为了进行自定义搜索,您需要在html中输入这些内容。您可以使用name和value属性传递到URL。
<input type="hidden" class="category" name="category_name" value="recording">
<input type="hidden" class="type" name="post_type" value="post">
<input type="text" class="search-bar" id="global-search"><button class="search-submit" type="submit" id="search-submit">
然后在脚本文件中,您将要构建URL。
// update search type
let type = $(\'input.type\').val();
if(type === 0 || type == undefined){
type = "";
}
// update search category
let category = $(\'input.category\').val();
if(category === 0 || category == undefined){
category = "";
}
// update search keyword
keyword = \'/?s=\' + $(this).val() + \'&post_type=\' + type + \'&category_name=\' + category;
$(\'.search-keyword\').attr(\'data-target\',\'/cimuk\' + keyword);
$(\'.search-keyword .label\').text(\'Search for \' + \'"\' + $(this).val() + \'"\');
//call this function on submit or enter
function goKeyword(){
window.location.href = $(\'.search-keyword\').data(\'target\')
}
然后可以将此筛选器添加到函数中。php。这将从URL中获取变量并将其传递给搜索查询。
//Search Post type
function mySearchFilter($query) {
$post_type = $_GET[\'post_type\'];
$category = $_GET[\'category_name\'];
if (!$post_type) {
$post_type = \'any\';
}
if (!$category){
$category = null;
}
if ($query->is_search) {
$query->set(\'post_type\', $post_type);
$query->set(\'category_name\', $category);
};
return $query;
};
add_filter(\'pre_get_posts\',\'mySearchFilter\');
搜索时应加载结果。php