WooCommerce normally uses product categories and tags to decide which related products to show on a single product page. Those recommendations can be very helpful for shoppers, but in some stores you may want to base the related product list on different criteria.
For example, you might want to recommend only products that match a custom field or products that have already performed well.
How to customize WooCommerce related products
WooCommerce retrieves related products through a standard WordPress query. That means we can intercept the result and replace it with a custom query that uses our own conditions.
add_filter('woocommerce_related_products', function ($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',
'posts_per_page' => $args['posts_per_page'],
'meta_query' => array(
array(
'key' => 'views',
'value' => 100,
'compare' => '>',
'type' => 'NUMERIC',
),
),
));
return wp_list_pluck($related_posts, 'ID');
}, 10, 3);
In this example, only products with a custom field value greater than 100 are used as related products. That kind of rule can help recommend more popular items and potentially improve the chance that users will click through and buy additional products.
Add the code to your theme’s functions.php file or to a plugin, and adjust the query logic to match the factors that matter most in your store.
