WooCommerce, by default, displays related products by category and tags. Because of these criteria, you cannot select which related products are offered to the customer. But, what if you want to group related products together by the product title? This article explains how to show WooCommerce related products by name.
WooCommerce Related Products by Name
In this article, we are going to explore brand names being used at the beginning of the product titles. For example, let us look at the following products:
Porter King/California King Panel Headboard
Porter Media Chest
Porter Dining Room Chair
Porter Coffee Table with Lift Top
Porter Dining Room Server
Porter Counter Height Bar Stool
Notice how “Porter” is the first word in each product title? It helps the customer identify the brand name. As a result, we are going to use the first word to filter which products are offered to the customer.
Here’s an example of a single product page with only “Porter” products in the related products section:
How to Show WooCommerce Related Products by Name
So how do you show Woocommerce related products by name on your website? Just copy and paste the following code snippet into your functions.php file:
The above code snippet uses the woocommerce_related_products filter to return WooCommerce related products by name. It is a modified version from Business Bloomer, which originally used the entire product title. However, the new snippet uses the first word of the product title instead.
Some of your product titles may not begin with the brand name. For example, you may have products with numbers or measurements before the brand name. If this is the case, insert the following before line 11:
$product_title = preg_replace( ‘/[0-9]+/’, ”, $product_title ); // Remove numbers
$product_title = str_replace( ‘Inch’, ”, $product_title ); // Remove unit of measurement
$product_title = str_replace( ‘inch’, ”, $product_title ); // Remove unit of measurement
$product_title = str_replace( ‘”‘, ”, $product_title ); // Remove unit of measurement
Likewise, substitute inches with feet, centimeters, or meters.
In short, you can remove any word from the product title by following the example above. This will allow you to show WooCommerce related products by name for your entire catalog.
The code snippet used in this example will require the product titles to begin with the same word. However, if using a brand, it should be a single word without spaces. This is a great alternative to show WooCommerce related products by name without having to use a separate plugin.
Need help? Our WordPress Development Service is a comprehensive solution for small, medium, and enterprise-level businesses. Call us at 602-633-4758 for a free consultation.
thank you for the code. What should I do to show products in the same category ? ‘include’ => array( $same_category ),
Hi Davetiye, here are the parameters for get_posts(): https://developer.wordpress.org/reference/functions/get_posts/