I want to remove or add some shipping options depending on the category of product that is in cart. For example: I have one product from category X and I want to add shipping-method-X to cart. And if I have one product from category X and one from another category, then shipping-method-X is disabled. Function below checks if array contains category with ID=49 and if there is another category, but it doesn't work. Nothing happens in cart :( Please help
add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
$tmp = array();
foreach ($terms as $term) {
array_push($tmp, $term->term_id);
}
array_unique($tmp);
if (sizeof($tmp) > 1 AND in_array('49', $tmp)) {
$found = true;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the categories.
if ( check_cart_for_share() ) {
// remove the method you want
unset( $available_methods['flat_rate'] );
}
// return the available methods without the one you unset.
return $available_methods;
}
答案 0 :(得分:0)
可能您的产品只属于ID为49的单一类别,这使您的if语句无效。您应该检查0个或更多条目。
if (sizeof($tmp) > 0 && in_array('49', $tmp)) { \\... it is in the array