Get related products SKUs in WooCommerce based on Products tags only

Viewed 35

We want to show a section called "complete the look" in WooCommerce. We are using PureClarity to do that.

PureClarity asked us to extend the WooCommerce feed by adding a code snippet in functions.php to add related peoducts SKUs under RelatedProducts.

We used the following code it is working but it is showing the related products SKUs based on product category and tags, however we need it to be based only on Products tag so it can show products that has the same tags but from different categories

Any help will be appreciated

/**
 * @param mixed[] $data - the array of data that will be sent to PureClarity
 * @param WC_Product $product - the WooCommerce product object
 * @return mixed
 */
function filter_pureclarity_feed_get_product_data( $data, $product ) {
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Initialize
        $skus = array();

        // Get product ID
        $product_id = $product->get_id();
        
        // Get related products based on product category and tags || second argument = limit of results, default = 5
        $related_products = wc_get_related_products( $product_id, 10 );

        // Loop through
        foreach ( $related_products as $related_product ) {
            // Get product 
            $product = wc_get_product( $related_product );

            // Get product SKU
            $product_sku = $product->get_sku();

            // NOT empty
            if ( ! empty( $product_sku ) ) {
                // Push to array
                $skus[] = $product_sku;
            }
        }

        $data['RelatedProducts'] = $skus;
    }
1 Answers

Apply below filter to remove categories from being queried:

add_filter( 'woocommerce_get_related_product_cat_terms', 'remove_related_cats', 10, 2 );
function remove_related_cats( $terms_ids, $product_id  ){
    return array();
}
Related