If you use get_search_link()
and someone filter the search URL and change it, get_search_link()
will return the filtered URL; that is the great of non-hardcoded URL. You or third party plugin may modify the URL and it will always return the correct value. So, issues 1 and 2 seems to not exist.
The issue 3 has different approachs:
1.- Use inputs in the search form with a name
equal to some query argument directly accepted by WP_Query
as query string. For example, 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.- Use whatever query string you want and hook WP_Query
on search request in pre_get_posts
action:
The 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>
And the action:
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 );
}
}
I would add the query string to WP Rewrite system:
add_filter( 'query_vars', 'cyb_query_vars' );
function cyb_query_vars( $vars ) {
$vars[] = 'a_search_filter';
return $vars;
}
Now you use get_query_var()
to get the value of the custom query variable:
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 );
}
}
Finally, you can get the current request and add/remove classes to your links and highliting them as you wish using CSS:
if( get_query_var( 'a_search_filter' ) == 'category1' ) {
$class="selected";
}
<a href="https://wordpress.stackexchange.com/questions/243976/..." class=".<?php esc_attr_e( $class ); ?>.">Category 1</a>