I’ve read the posts on WP SA on rewrites and custom post types, but I can’t figure out why my search for 2 different post types isn’t working.
I’d like my URLS to become example.com/search/events/searchtem
and example.com/search/artists/searchterm
.
I have a CPT called ‘events’ and one called ‘artists’. My custom permalink structure is set to /%postname%/
.
My search forms:
<form class="search-form" action="<?php echo home_url('/events/'); ?>" method="get">
<input id="s" name="s" type="text" class="span4" />
<input class="search-button" type="submit" value="Zoek" tabindex="-1" />
</form>
<form class="search-form" action="<?php echo home_url('/artists/'); ?>" method="get">
<input id="s" name="s" type="text" class="span4" />
<input class="search-button" type="submit" value="Zoek" tabindex="-1" />
</form>
If I search, the URLs become example.com/events/?s=searchterm
and example.com/artists/?s=searchterm
but the return a 404. This is weird, because putting ?s=
behind any URL turns it into a query right? These are the results with the nice-search functions (see below) disabled or enabled (no difference).
If I change <?php echo home_url('/events/'); ?>
to <?php echo home_url('/'); ?>
and add <input type="hidden" name="post_type" value="events" />
with nice-search (see below) disabled everything works as expected (URL becomes example.com/?post_type=events&s=searchterm
). With nice-search enabled, the results become example.com/search/searchterm (so it does rewrite) and it does take me to my search results page but it searches everything instead of just one post type.
The functions from nice-search (I’m using the roots theme) which consists of two parts:
function roots_nice_search_redirect() {
global $wp_rewrite;
if (!isset($wp_rewrite) || !is_object($wp_rewrite) || !$wp_rewrite->using_permalinks()) {
return;
}
$search_base = $wp_rewrite->search_base;
if (is_search() && !is_admin() && strpos($_SERVER['REQUEST_URI'], "/{$search_base}/") === false) {
wp_redirect(home_url("/{$search_base}/" . urlencode(get_query_var('s'))));
exit();
}
}
if (current_theme_supports('nice-search')) {
add_action('template_redirect', 'roots_nice_search_redirect');
}
and
function roots_request_filter($query_vars) {
if (isset($_GET['s']) && empty($_GET['s'])) {
$query_vars['s'] = ' ';
}
return $query_vars;
}
add_filter('request', 'roots_request_filter');
After reading the posts, I think I need to alter my rewrite function but I don’t really know how to…
Also, I’d like to use <?php echo home_url('/events/'); ?>
instead of <input type="hidden" name="post_type" value="events" />
if possible and I don’t use pagination.