So far in my wordpress installation I have a complete wordpress search page that I can call by going to:
/?s=mysearchstring
And this searches through wordpress pages containing the “mysearchstring
” string.
So I have created a new page “Custom Search” (/custom-search/
) and assigned a template file custom-search.php
(same code as search.php
).
How can I add a keyword parameter to this?
/custom-search?s=mysearchstring
doesn’t quite work, it only shows 404 Page Not Found, while /custom-search/
displays a search page as an only result.
custom-search.php
code:
<?php
/*
Template Name: Custom Search
*/
//Post ID
global $wp_query;
$content_array = $wp_query->get_queried_object();
if(isset($content_array->ID)){
$post_id = $content_array->ID;
}
else $post_id=0;
$template_uri = get_template_directory_uri();
//Search
$allsearch = &new WP_Query("s=$s&showposts=-1");
$count = $allsearch->post_count;
wp_reset_query();
$hits = $count == 1 ? $count." ".__("hit for","goodweb") : $count." ".__("hits for","goodweb");
get_header();
?>
along with the html listout.
What can I do to pass the parameter search query to this 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:
/custom-search?cs=mysearchstring
then inside the page template use the variable$_GET['cs']
instead of the variable$_GET['s']
/?s=mysearchstring
but hooking'template_include'
to usecustom-search.php
instead ofsearch.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: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
addDoing 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 setposts_per_page
to -1 usepre_get_posts
:And in your
custom-search.php
use: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:
A
GET
string will work just like in any other PHP application but you cannot use a query parameter that WordPress uses. That is the problem here. WordPress already usess
. Use something else, like ‘mys’.Honestly, though, your custom search looks pretty much like a normal search so I don’t really understand why you are doing this.