我前面的答案告诉你is_search()
在代码中。
为了解决您的问题,您可以尝试从搜索表单中添加一些数据。在WordPress中,您有一个搜索表单。php,您可以编辑此文件以添加新的隐藏字段,或使用丑陋的筛选函数,就像我在这里所做的那样:
// Gives you the category where you want to search with from page ID
add_filter(\'wpse_306057_search_category_id\', \'wpse_306057_search_category_id\', 10, 1);
function wpse_306057_search_category_id($id = false) {
switch($id)
{
case 100:
$cat_id = 37;
break;
case 200:
$cat_id = 24;
break;
case 201:
case 202:
case 203:
$cat_id = array(57,99); // You may use multiple cats
break;
default:
$cat_id = false;
break;
}
return $cat_id;
}
// Add input hidden with "from page" for your search form
add_filter(\'get_search_form\', \'wpse_306057_search_category_input\', 10, 1);
function wpse_306057_search_category_input($form) {
return str_replace(\'</form>\', \'<input type="hidden" name="search_from_page" value="\'.get_queried_object_id().\'" /></form>\', $form);
}
// Add cat to your query
add_filter(\'pre_get_posts\', \'wpse_306057_search_category\', 10, 1);
function wpse_306057_search_category($query) {
if(!is_admin()
&& $query->is_main_query()
&& $query->is_search()
&& !empty(@$_GET[\'search_from_page\'])
&& apply_filters(\'wpse_306057_search_category_id\', $_GET[\'search_from_page\']))
{
$query->set(\'cat\', apply_filters(\'wpse_306057_search_category_id\', $_GET[\'search_from_page\']));
}
}
我还没有测试代码,但这是一种很好的方式来实现您想要实现的目标。