Tips For Search.php and Its Searchform Script in WordPress

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 $s to 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); ?>
<div id="search-phrase">

<?php _e('We found the following posts that matched your search criteria: ' . "$s"); ?>

  • Target the search results in style.css with the new id or class. Applying an id to the wrapping div lets you target the leading text of the search results in your style.css stylesheet. In the example above the stylesheet could be used to style div#search-phrase to draw the reader’s attention.
  • Use wp_specialchars() when calling for variables returned by searchform.php. Echoing <?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!

Leave a Reply

Your email address will not be published. Required fields are marked *