Fix Empty Searches


One minor problem for any web site is duplicate content: the same resource is available under different URIs. Yes, we have <link rel=canonical>, but anything that prevents such cases is better.

Today, let’s look at something, that most professionals never see: empty searches. You offer a search input field, and someone hits the submit button unintentionally, without any term entered. The resulting URI looks like this: example.com/?s=. It shows the same content as your front page. In fact, it is the front page.

No one needs that.

Therefore, I have added a simple rule to my .htaccess:

# Catch empty searches
RewriteCond %{QUERY_STRING} ^s=$
RewriteRule ^ /? [L,R=301]

Add these lines right after the RewriteBase directive.

Next, I wanted to save my visitors the unnecessary request. I have written a simple jQuery plugin:

/**
 * Stop empty searches
 *
 * @author Thomas Scholz http://toscho.de
 * @param  $ jQuery object
 * @return bool|object
 */
(function( $ ) {
   $.fn.preventEmptySubmit = function( options ) {
       var settings = {
           inputselector: "#s",
           msg          : "Don’t waste your time with an empty search!"
       };

       if ( options ) {
           $.extend( settings, options );
       };

       this.submit( function() {
           var s = $( this ).find( settings.inputselector );
           if ( ! s.val() ) {
               alert( settings.msg );
               s.focus();
               return false;
           }
           return true;
       });
       return this;
   };
})( jQuery );

I call it in my footer scripts:

jQuery( "#searchform" ).preventEmptySubmit();

Note that my search form element has an id attribute with the value searchform. Adjust the selector to match your current theme. To change the message, just add an option for it:

jQuery( "#searchform" ).preventEmptySubmit({ msg: "This won’t work!" });

You may use the script for other input elements too. Set the selector in the second option inputselector. Say, you have a form with the id discountcode and a field with the id dcodenumber:

jQuery( "#discountcode" ).preventEmptySubmit(
{
   msg: "No number, no discount, sorry!",
   inputselector: "dcodenumber"
});

Useful? Any hints?

Guest Post

This post is written by Thomas Scholz – toscho.de and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Thomas.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


Posted

in

by

Comments

One response to “Fix Empty Searches”

  1. […] Frank at WPEngineer has a tip up to fix empty searches within WordPress. […]