Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialStefaan Quackels
5,720 PointsSearch Form For Blogposts
So, let's say we do haven an extensive library of blogposts. Then a searchbar becomes necessary.
How can we make sure only the blogposts will be displayed using this searchbar and not the pages?
Should we copy the loop from, for example, the home.php-template into the search.php file? If this is correct can we adjust the loop with a WP_query? Which parameter should we use then??
1 Answer
Joel Bardsley
31,249 PointsYou can modify the search form's behaviour by adding hidden input fields to its html. If your theme folder doesn't already have a searchform.php file, create a new one using the code from here as a reference.
To limit the search to just 'posts', you could add this input field before the submit button:
<input type="hidden" value="post" name="post_type" id="post_type" />
// value can be a custom post type if you are using them.
More information on some other hidden fields that can be used to change the search form's behaviour can be found here
If you're not comfortable doing it this way, you could alternatively add a function to your functions.php file that uses filters to change the search form's html. Some example code for this can be found at the bottom of this page
If you need further information about either technique let me know.
Stefaan Quackels
5,720 PointsStefaan Quackels
5,720 PointsThat's great Joel. Got it to work perfectly. Thanks!