WooCommerce displays related products on the product detail page based on product categories and tags. Related products can recommend additional items that users may be interested in, which is very important for the shopping experience. Sometimes, however, we may want to define related products according to other conditions, such as only showing products that contain a certain custom field.
How to Customize WooCommerce Related Products
First, we know that the method WooCommerce uses to retrieve related products is a standard WordPress query. That means we can modify this query and add our own conditions in order to customize how related products are selected.
Let’s look at an example:
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',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_key' => 'views',
'meta_value' => '100',
'meta_compare' => '>'
'exclude' => array( $product_id ),
));
return $related_posts;
}, 9999, 3 );In this code, we add a custom field query condition so that only related products with more than 100 views are displayed. This helps ensure that the recommended items are relatively popular products. A setup like this can improve the user’s interest in related products to some extent and may help increase sales.
Put the code above into your theme’s functions.php file and it will take effect. If you are building a plugin instead, placing the same code in the appropriate part of your plugin will achieve the same result.
