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;
}
Likely your product is only in a single category with the ID of 49 which makes your if statement invalid. You should check for 0 or more entries.
if (sizeof($tmp) > 0 && in_array('49', $tmp)) { \\... it is in the array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.