Search code examples
phphook-woocommercecode-snippets

Remove duplicate from snippet shop loop woocommerce


I have variable products which have two attributes: size and color. When some product has attributes M->red, XL->blue, M->yellow. Below snippet show atrributess M L M and it's ok but I can't find solution how remove duplicate items

add_action('woocommerce_before_shop_loop_item_title', 'variations_loop');
function variations_loop() {
    global $product;
    if($product->get_type() == 'variable') {
        foreach($product->get_available_variations() as $key) {
            $variation = wc_get_product($key['variation_id']);
            echo $variation -> attributes['pa_size'];
        }
    }
}

Solution

  • Based on your comments, it sounds like you have the following array:

    [
        [
            "pa_size" => "m",
            "pa_color" => "blue"
        ],
        [
            "pa_size" => "xl",
            "pa_color" => "yellow"
        ],
        [
            "pa_size" => "m",
            "pa_color" => "blue"
        ]
    ]
    

    What you will need to do is call array_map (documentation) to get just the sizes and array_unique (documentation) to get the unique values.

    Once you get those unique values, you can optionally get the products by the size by using array_filter (documentation).

    Here is an example:

    // define the products
    $products = [
        [
            "pa_size" => "m",
            "pa_color" => "blue"
        ],
        [
            "pa_size" => "xl",
            "pa_color" => "yellow"
        ],
        [
            "pa_size" => "m",
            "pa_color" => "blue"
        ]
    ];
    // get just the "pa_size" values
    $productSizes = array_map(function($key, $value) {
        return $value["pa_size"];
    }, array_keys($products), array_values($products));
    // get the unique "pa_size" values
    $uniqueProductSizes = array_unique($productSizes);
    
    // loop over the unique "pa_size" values
    foreach ($uniqueProductSizes as $key => $value) {
        // get every product by the "pa_size"
        $productsBySize = array_filter($products, function($innerKey) use ($value) {
            return $value === $innerKey["pa_size"];
        });
    }
    

    Fiddle: https://onlinephp.io/c/d637f