Home > database >  Remove duplicate from snippet shop loop woocommerce
Remove duplicate from snippet shop loop woocommerce

Time:01-24

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'];
        }
    }
}

CodePudding user response:

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

CodePudding user response:

Your solution works but not for me. I don't know where is the problem. Below snippet and example responde.

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']);      
            $varation_size = $variation -> attributes;      
            var_dump($varation_size);           
        }
    }
}

array(2) {
  ["pa_size"]=>
  string(1) "m"
  ["pa_color"]=>
  string(4) "blue"
}
array(2) {
  ["pa_size"]=>
  string(2) "xl"
  ["pa_color"]=>
  string(6) "yellow"
}
array(2) {
  ["pa_size"]=>
  string(1) "m"
  ["pa_color"]=>
  string(4) "blue"
}
  • Related