如果您使用get_search_link()
还有某人filter the search URL 改变它,get_search_link()
将返回过滤后的URL;这就是非硬编码URL的优点。您或第三方插件可以修改URL,它将始终返回正确的值。因此,问题1和2似乎不存在。
问题3有不同的方法:
1.-将搜索表单中的输入与name
等于直接接受的某个查询参数WP_Query
作为查询字符串。例如category_name
:
<form class="search" method="get" action="<?php echo get_search_link(); ?>" role="search">
<input class="search-input" type="search" name="s">
<select name="category_name">
<option value="">All categories</option>
<option value="politics">Politics</option>
<option value="economy">Economy</option>
</select>
<button class="search-submit" type="submit" role="button">Search</button>
</form>
2使用所需的任何查询字符串并挂钩
WP_Query
在中搜索请求时
pre_get_posts
措施:
HTML:
<form class="search" method="get" action="<?php echo get_search_link(); ?>" role="search">
<input class="search-input" type="search" name="s">
<select name="a_search_filter">
<option value="">All categories</option>
<option value="politics">Politics</option>
<option value="economy">Economy</option>
</select>
<button class="search-submit" type="submit" role="button">Search</button>
</form>
以及行动:
add_action( \'pre_get_posts\', \'cyb_advanced_search\' );
function cyb_advanced_search( $query ) {
if ( ! is_admin() && $query->is_search && $query->is_main_query() ) {
// Set query parameters you need
// For example
$search_filter = $_REQUEST[ \'a_search_filter\' ];
$tax_query = [
\'taxonomy\' => \'news\',
\'field\' => \'slug\',
\'terms\' => sanitize_text_field( $search_filter ),
];
$query->set( \'tax_query\', $tax_query );
}
}
我会将查询字符串添加到WP重写系统:
add_filter( \'query_vars\', \'cyb_query_vars\' );
function cyb_query_vars( $vars ) {
$vars[] = \'a_search_filter\';
return $vars;
}
现在您使用
get_query_var()
要获取自定义查询变量的值,请执行以下操作:
add_action( \'pre_get_posts\', \'cyb_advanced_search\' );
function cyb_advanced_search( $query ) {
if ( ! is_admin() && $query->is_search && $query->is_main_query() ) {
// Set query parameters you need
// For example
$search_filter = get_query_var( \'a_search_filter\' );
$tax_query = [
\'taxonomy\' => \'news\',
\'field\' => \'slug\',
\'terms\' => sanitize_text_field( $search_filter ),
];
$query->set( \'tax_query\', $tax_query );
}
}
最后,您可以获取当前请求,并将类添加/删除到链接中,并根据需要使用CSS对其进行高级化:
if( get_query_var( \'a_search_filter\' ) == \'category1\' ) {
$class = \'selected\';
}
<a href="..." class=".<?php esc_attr_e( $class ); ?>.">Category 1</a>