Home » WooCommerce: Custom Related Products

WooCommerce: Custom Related Products

by Tutor Aspire

WooCommerce picks related products on the Single Product Page based on product categories and/or product tags. Related products are very important to the shopping experience, and sometimes this is not enough – what if you want to automatically show certain products based on different criteria?

So, here’s a quick snippet to e.g. get related products with the same product title of the current one. A very strange example, but you can use this as reference in case you want to get products based on different criteria.

The get_posts() function, in fact, can be customized to get products with a given stock, specific price range, same custom field value, search term, and so on.

In this screenshot, I’m getting Related Products by search title string = “Simple”. All products that include “Simple” in their title will be considered as related.

PHP Snippet: Custom Related Products @ WooCommerce Single Product Page

/**
 * @snippet       Get Related Products by Same Title @ WooCommerce Single
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.8
 * @donate $9     https://tutoraspire.com
 */

add_filter( 'woocommerce_related_products', 'tutoraspire_related_products_by_same_title', 9999, 3 ); 

function tutoraspire_related_products_by_same_title( $related_posts, $product_id, $args ) {
$product = wc_get_product( $product_id );
$title = $product->get_name();
$related_posts = get_posts( array(
'post_type' => 'product',
'post_status' => 'publish',
'title' => $title,
'fields' => 'ids',
'posts_per_page' => -1,
'exclude' => array( $product_id ),
));
return $related_posts;
}

You may also like