Reputation: 183
I have some meal packages to sell. For example. Chicken meal has variations: 10 pack, 14 pack, 18 pack. I want to disable flat_rate:3 when people order 10 pack. But I don’t know how to get the variation. My code is below:
function hide_one_delivery( $rates, $item_id ) {
global $woocommerce, $product;
$10_pack = 0;
foreach ( $woocommerce->cart->cart_contents as $product ) {
$variation_data = $product->get_variation_attributes();
$variation_detail = woocommerce_get_formatted_variation( $variation_data, true );
if( $variation_detail == "10 pack" ){
$10_pack += 1;
}
}
if ($10_pack > 0){
unset( $rates['flat_rate:3'] );
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_one_delivery', 100 );
It's not working. Can anyopne please help?
Upvotes: 0
Views: 3742
Reputation: 15
This code will allow you to add the variation to your cart.php page. My example has a name because I name my Variation "PkgDesc" when I added it to the Cart Session. This is code that you need to add to the Cart.php page.
Add the line of code after the foreach() line (around line 48):
$pkgDesc= apply_filters( 'woocommerce_cart_item_product_id', $cart_item['variation'], $cart_item, $cart_item_key );
Now add the code below after your product title (// Meta data) (around line 85)
echo ": ";
echo $pkgDesc['PkgDesc'];
Your Cart line item will now look like this:
Chicken meal: 10 pack
Upvotes: 0
Reputation: 1164
Just look into the product array, and you can get the variation data from the product array.
function hide_one_delivery( $rates, $item_id ) {
global $woocommerce;
foreach ( $woocommerce->cart->cart_contents as $product ) {
//$product is a array, and 10-pack is the slug of the attribute name
if ( $product['variation_id'] && in_array('10-pack', $product['variation']) ) {
unset( $rates['flat_rate:3'] );
break;
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_one_delivery', 100, 2 );
Upvotes: 1