I’ve been struggling to find the best solution for a better (custom) search. I’m using WordPress for a large Media Catalog, so my intention is to provide better search options.
So far I’ve been able to put various search forms in the archive.php that perform search by: subcategory, tag, custom field(autor) and year, all within the same Archive Category.
I’m posting this here to see if there’s any body out there that would like to improve or use what I’ve done so far.
What I hate about it is having different forms for each type of search, I feel it’s not user friendly at all. Perhaps somebody could help me out to build a better solution.
Eventually I’ll integrate this with jQuery to see if it can get any better, but first I want to clean up my code, I’m thinking that there could be easier and better ways to do the markup of what I’ve done.
Forget about multiple forms….
UPDATE
FORM:
<?php
// Current URL for setting up Search Form Action
global $wp;
$current_url = get_home_url(null, $wp->request, null);
?>
<form role="search" method="get" action="<?php echo $current_url; ?>/">
<input type="hidden" name="s" value="true" />
<!-- General Search -->
<label for="s">General</label>
<input type="text" name="s" />
<!-- Tag Search -->
<label for="tag">Tag</label>
<input type="text" name="tag" />
<!-- Autor Search -->
<label for="autor">Autor</label>
<input type="text" name="autor" />
<input value="Buscar" type="submit">
</form>
FUNCTION
// Extend Search
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set( 'tag', $query->query_vars['s'] );
$query->set( 'meta_key' , 'autor' );
$query->set( 'meta_value' , $query->query_vars['s'] );
} } }
add_action('pre_get_posts','search_filter');
You only need one form and a callback on
pre_get_posts
. For example:Now your callback:
You should validate that code. You have strange things happening, like multiple
id
attributes on some elements and put that Javascript in a file and enqueue it.In case it comes handy for anyone.
My goal was to inlcude an enhaced/better search, providing other fields for tag and custom field search.
The following form is inserted in archive.php,
$categoria_id
being the current archive category:In functions.php I inserted the following function, as suggested by @s_ha_dum