We recently built a WordPress / WooCommerce website for a client to help them sell their product online. WooCommerce does a great job at displaying groups of products in nice neat grids when you’re looking at categories, but when you do a search, the system refused to make the “assumption” that we wanted to search for products only and displayed the results as general posts (a long list instead of a product grid). This would be fine if our website was a mix of blog posts and products, but the client wanted all search results to be limited to products, but we couldn’t find a way to force this.

So when you went to https://thediecastpub.com/?s=mustang, you got this ugly result:

If you appened the “post_type” querystring, we got the results we wanted (https://thediecastpub.com/?post_type=product&s=mustang):

We looked for a plugin or other type of fix and couldn’t find one. I’m sure we could have altered the theme or even added some PHP in the search routine, but we were looking for something a bit cleaner.

.htaccess to the rescue! I’m sure someone will tell me this isn’t the proper way to do this, but I needed to rewrite a URL, and this did the trick. Here’s the code we used and explanations of the key lines:

# BEGIN Search results in grid
<IfModule mod_rewrite.c>
RewriteEngine On 
RewriteCond %{QUERY_STRING} s=? 
RewriteCond %{QUERY_STRING} !(^|&)post_type=product(&|$) [NC] 
RewriteRule ^ %{REQUEST_URI}?post_type=product [L,QSA,R] 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|public|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [L]
#END Search Results in grid

Here’s what some of the key lines do:

  • RewriteCond %{QUERY_STRING} s=?
    This line ensures we’re talking about query strings involving “s={something}” (in other words… a search.
  • RewriteCond %{QUERY_STRING} !(^|&)post_type=product(&|$) [NC]
    This line makes sure we haven’t already appended a “post_type” value to the query string (duplication, and LOOPS!)
  • RewriteRule ^ %{REQUEST_URI}?post_type=product [L,QSA,R]
    This line appeents the post type to the query string.
  • RewriteCond %{REQUEST_FILENAME} !-f
    This line makes sure we aren’t referencing a direct file name.
  • RewriteCond %{REQUEST_FILENAME} !-d
    This line makes sure we aren’t referencing a direct directory name.
  • RewriteCond $1 !^(index\.php|public|images|robots\.txt|css)
    This line makes sure we aren’t referencing a special file.
  • RewriteRule ^(.*)$ index.php/$1 [L]
    And this line finishes things up.

There’s not too much fancy about this, but it gets the job done. I welcome your feedback on this creative solution.

Need help with your own e-commerce site? Let’s talk!

Error: Contact form not found.