Loading...

I was working on a WordPress site using the popular WooCommerce plugin today and was presented with the problem of trying to differentiate between a WordPress category and a WooCommerce product category.
WooCommerce products don’t have a WordPress category just as a standard blog post on the site doesn’t have a WooCommerce shop category, the two things aren’t linked. This is normally not a problem, however the search page was returning both blog posts and shop products in its results. I wanted to display a simple button linked to the product page on the shop if the search item was a WooCommerce product or display the text excerpt if the item was a blog post. This turned out to be quite straightforwards!
After having a good root around through the WooCommerce support documentation I was no closer to finding a quick function that did the equivalent of the WordPress code:

the_category()

So after some trial and error with the is_category() and in_category() functions, I began looking at the $post variable in the post loop as that was the variable populating the list. Sure enough $post->post_type was exactly what I was looking for and defined between pages, products and posts for each item.

I plugged that into a quick if statement and plugged it into the search.php file (it might be different depending on your theme but I copied it under the the closing h2 tag for the_title):


This is code I copied instead:

<?php if ( $post->post_type == 'product' ) { ?>
<p class="woocommerce"><a class="button" href="<?php the_permalink() ?>;">BUY NOW</a></p>

Now when any products show up the search results they have a nice button directing them straight to the item in the shop, and blog posts & pages display the excerpt text. You can change ‘product’ to ‘page’ or ‘post’ to alter the output for those types as well.

Latest Posts

Portfolio

Contact

Fill in the form below to send us a message. Your details will not be used for promotional purposes or passed on to any third parties.

 

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close