-1

Is it possible to pass variable to get_search_form()?

I'm using it in two places: one in header and on the search page in the content. The latter must have additional class, e.g. search--full. I've tried to use is_search() but while it works well on other pages, on search page both forms have search--full class.

4
  • Under what conditions does the class need to be search--full. What variable do you want to use? Nov 25, 2017 at 2:01
  • @JacobPeattie under no conditions actually, it depends on where the search form appears: if it’s in the header → no class, if it’s in the main → add class.
    – Runnick
    Nov 25, 2017 at 11:21
  • Are you hard-coding the form into these places, or trying to respond to where a user might have placed it? Nov 25, 2017 at 11:53
  • I am hard-coding.
    – Runnick
    Nov 25, 2017 at 13:02

2 Answers 2

0

You can pass custom args to get_search_form() when calling it:

get_search_form(array('test' => 'hello'))

Then in searchform.php it all will be available under $args variable

echo($args['test']); // Will print "hello"

Just be aware in your searchform.php file that this file is called everywhere get_search_form() is used so you most likely want to check that such key exists first

if(array_key_exists('test', $args)){
   echo($args['test']); 
}
0

a more proper way to solve this as pointed in many cases would be :

//include search form in header
include(locate_template('template-header-search.php'));
//include search form in body
include(locate_template('template-body-search.php'));
3
  • Wouldn't it require to create two templates?
    – Runnick
    Nov 24, 2017 at 20:28
  • get_template_part() would be the preferred way of including a template. Nov 25, 2017 at 2:02
  • 1
    @Runnick Yes it would require two templates but you can tweak that add a global variable to differentiate between which one
    – sdx11
    Nov 26, 2017 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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