2

I have a search form in the home page and search form in the sidebar. Is it possible to make the search form in the home page show results as per a specific template and make the sidebar search form show a different template?

i want to make the homepage search box to show results in different way. Its a custom post. so if user uses that form it should only have data from that custom post. But the default wordpress search box in the sidebar should get the results from entire website.

eg. listing search page results with map

Thanks

  • As in, if you search from the home page, the page you're displaying results on is different from the one in the sidebar? – phatskat Aug 31 '18 at 19:58
  • Now they both have the same template – Latheesh V M Villa Aug 31 '18 at 20:15
  • Do the search forms actually search for anything different? What's the difference, if any, between the forms? – Jacob Peattie Sep 1 '18 at 2:27
  • @JacobPeattie Yes one search is for a custom post and another for default one. – Latheesh V M Villa Sep 1 '18 at 2:31
  • And what are the requests sent by these forms? Can you tell which is which based on GET params? – Krzysiek Dróżdż Sep 1 '18 at 5:07
2
+50

You can restrict a search to a custom post type by modifying a basic WP search form like this:

<form id="cptsearch" action="<?php echo home_url(); ?>" method="get">
    <input type="text" name="s" />
    <input type="hidden" name="post_type" value="POSTTYPENAME" />
    <input id="searchsubmit" type="submit" alt="Search" value="Search" />
</form>

To select a specialized template for the custom post type search, add this filter in your functions file:

function template_chooser($template) {
    global $wp_query;
    $post_type = get_query_var('post_type');
    if( $wp_query->is_search && $post_type == 'POSTTYPENAME' ) {
    return locate_template('page_POSTTYPENAME.php');
    }
    return $template;
}
add_filter('template_include', 'template_chooser');

And of course, you must create the specialized search results template: page_POSTTYPENAME.php

  • Hello, thanks but it seems the index.php is getting loaded instead template "page_POSTTYPENAME & there is no search results when in am using the form. – Latheesh V M Villa Sep 4 '18 at 21:33
  • 1
    My mistake: try using this for hidden field in search form: <input type="hidden" name="post_type" value="l" /> – Ray Gulick Sep 5 '18 at 1:32
  • 1
    Try substituting this: – Ray Gulick Oct 15 '18 at 13:40
  • 1
    for action, between php brackets: echo home_url(); – Ray Gulick Oct 15 '18 at 13:47
  • 1
    If that works for you, please let me know. – Ray Gulick Oct 15 '18 at 13:48

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.