The more you twiddle with WordPress the more you will learn about it. Makes sense, yes? Read on for a couple tips on coding and styling the WP search function.
Check out these search function tricks for your WP blog:
- Use the right path in the call to the
searchform.php. While you want to search all the important text on your blog, you don’t want your visitors to search your entire server. Some pages may have
<?php echo $_SERVER ['PHP_SELF']; ?>as the value for the action attribute of the search form and that could enable a search of the entire server. Restrict the search to the content of your blog by using
<?php bloginfo ('home'); ?>instead.
- Modify search.php to allow for personalization or styling of the search output. Wrap a div around the output to be able to stylize the content with a new id or class. For instance, the following code assigns the value of the variable
$sto the value of the search term with any special characters stripped from it. The code also specifies the leading text that appears when search results are returned to the screen. Try searching for a term in this blog to see the output.
<?php $s = wp_specialchars($s, 1); ?>
<?php _e('We found the following posts that matched your search criteria: ' . "$s"); ?>
- Target the search results in
style.csswith the new id or class. Applying an
idto the wrapping
divlets you target the leading text of the search results in your
style.cssstylesheet. In the example above the stylesheet could be used to style
div#search-phraseto draw the reader’s attention.
wp_specialchars()when calling for variables returned by
<?php echo $s; ?>is a bad practice because it may allow malicious code injection. When returning values from any database make sure to use
wp_specialchars()to first strip any “special characters” before outputting to the screen.
Keep reading and learning!