Ecommerce Shopify WordPress Discussion

WooCommerce show random related products from other categories if product is in category with only one product

I have a WooCommerce product for which I would like to show four random related products from the store, because the product itself is alone in a category. I found this great script which almost works, but sometimes I get one, sometimes two, three, four related products on page reload. Any idea how to get a fixed number of four related products? add_filter( 'woocommerce_related_products', 'filter_woocommerce_related_products', 10, 3 ); function filter_woocommerce_related_products( $related_posts, $product_id, $args ) { // Show products $show_products = 4; // Initialize $taxonomy = 'product_cat'; // When empty if ( empty( $related_posts ) ) { // Get WooCommerce product categories WP_Term objects $product_cats_ids = get_terms( array( 'taxonomy' => $taxonomy, 'fields' => 'ids', ) ); // Get product id(s) from a certain category, by category-id $product_ids_from_cats_ids = get_posts( array( 'post_type' => 'product', 'numberposts' => $show_products + count( $args['excluded_ids'] ), 'post_status' => 'publish', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'id', 'terms' => $product_cats_ids, 'operator' => 'IN', ) ), 'orderby' => 'rand', 'exclude' => $args['excluded_ids'], )); // Extract a slice of the array $related_posts = array_slice( $product_ids_from_cats_ids, 0, $show_products ); } // Return return $related_posts; }
TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.