How to pass a search $_GET parameter to a new custom search page?

Problem is that 's' param is a standard query param of WordPress, when you use the url /custom-search?s=mysearchstring your are saying to WordPress to retrieve the page 'custom-search' that contain the string 'mysearchstring' and this bring a 404.

You have 2 possibilities:

  1. use another query string name, something like /custom-search?cs=mysearchstring then inside the page template use the variable $_GET['cs'] instead of the variable $_GET['s']
  2. send all your searchs to home url: /?s=mysearchstring but hooking 'template_include' to use custom-search.php instead of search.php. This can be done without creating a page ‘custom-search’.

Solution 1

Only thing you have to do is using the query string 'cs' instead of 's', then inside your template use:

// ...
$s = filter_input(INPUT_GET, 'cs', FILTER_SANITIZE_STRING);
$allsearch = &new WP_Query("s=$s&showposts=-1");
// ...

Solution 2

Delete the page ‘custom-page’ that use the template "Custom Search": you don’t need it. You can remove the template headers at all, if you want.

Send all your search requests to /?s=mysearchstring.

Now to your functions.php add

add_filter('template_include', 'my_custom_search_template');

function my_custom_search_template( $template ) {
  if ( is_search() ) {
    $ct = locate_template('custom-search.php', false, false);
    if ( $ct ) $template = $ct;
  }
  return $template;
}

Doing so all the search requests will be displayed using your custom-search.php (if it exists). Note that the search is already done in main query, so you do not need to run it again, if you want to set posts_per_page to -1 use pre_get_posts:

add_action('pre_get_posts', 'search_no_paging');

function search_no_paging( $q ) {
  if ( $q->is_main_query() && $q->is_search() && ! is_admin() ) {
    $q->set('posts_per_page', -1);
  }
}

And in your custom-search.php use:

global $wp_query;
$count = $wp_query->post_count;
$hits = $count == 1 ? $count." ".__("hit for","goodweb") : $count." ".__("hits for","goodweb");
get_header();

while( have_posts() ) { the_post();
  // your loop here
}

As you can see you do not need to run a custom query because the main query does the work.


Solution 1 is the best choice if you want to show the page content alongside the search results, but if you are creating that page with no content, with the only aim to use the custom template for search results, the solution 2 is better because:

  1. is theme independent: code can be put in a plugin and used with any theme, and also doesn’t need that page to be created on the backend
  2. is more performant: if you use solution 1, two queries are run, the first to get the page, the second to get search results; using solution 2 only one query is run

Leave a Comment