'Remove Already Displayed WooCommerce Related Products

When using 2 related product loops on the same single product page, is it possible to exclude the products in 1 loop from being duplicated in the 2nd loop.

By default, the related products display after the single product however what if you also want to display another loop before the single product with different related products that aren't already displayed in the other related products loop

I was thinking about adding custom code like this to the related products loop but don't know how or whether there's already code included that can be used to do this.

$exclude[] = $post->ID; 

And then this :

'post__not_in'  =>  $exclude,

I also tried this code but i don;t know how to add the code to the loop so i can use the filter.

add_filter( 'woocommerce_related_products', 'exclude_related_products', 10, 3 );
function exclude_related_products( $related_posts, $product_id, $args ){


    $exclude_ids = array($exclude);

    return array_diff( $related_posts, $exclude_ids );
}

So i guess i also need to find out how to add the code to store the already displayed product id's to the related products loop.

Or maybe i just need to filter and add a custom query arg to :

woocommerce_product_related_posts_query


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source