Ndugu
1
Hi,
I got the site search up and running, but instead of a search page, I want to put a search field into a menu.
So I made a snippet and hooked it up into the menu. This is the code:
<form>
<input type="search" name="q" value="<?php echo esc($query) ?>">
<input type="submit" value="Suche">
</form>
<ul>
<?php foreach($results as $result): ?>
<li>
<a href="<?php echo $result->url() ?>">
<?php echo $result->title()->html() ?>
</a>
</li>
<?php endforeach ?>
</ul>
But, I get this error message for line 2:
Undefined variable: query
<input type="search" name="q" value="<?php echo esc($query) ?>">
I guess it has something to do with the logic that is in the controler, so I put that code into the snippet, but that idea was even worse.
I suppose you still want to show the results in the search page?
Then the logic stays in the controller as before.
But you have to put the link to the search page in the action attribute of the form, otherwise it will use the current page.
<form class="search" method="post" action="<?= page('search')->url() ?>">
Ndugu
3
Unfortunately the error message persisted:
Undefined variable: query
<input type="search" name="q" value="<?php echo esc($query) ?>">
You are right. The search controller only loads for the search template. Because of that the variable $query
is undefined for all other templates.
You could ommit the default value or try to check if it exist. This should work …
<input type="search" name="q" value="<?php echo (!empty($query)) ? esc($query) : '' ?>">
Ndugu
5
Waaa ! It wa-wa-works!
Thank you very much for your explanation! That triggered the idea, that I had to remove the form for the search results out of the snippet - et voilà.