woocommerce_package_rates not firing with plugin
-
Hello,
I’m trying to apply a custom filter to show specific shipping methods according to the presence of a category or product id using the hook “woocommerce_package_rates”, but it doesn’t seems to trigger when using in combination with your plugin.
Is there any other hook to use or setting to apply so that it can work?
Actual code (remains untested):
function filter_shipping_methods($rates, $package) { // Get the products in the cart $cart = WC()->cart->get_cart(); // Define the shipping methods allowed by default $allowed_shipping_methods = array(); // Loop through the products in the cart foreach ($cart as $item) { // Get the product ID $product_id = $item['product_id']; // Get the product categories $categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids')); // Check if the product or its categories match the criteria if ($product_id == 37683 || $product_id == 38945 || $product_id == 25158 || $product_id == 38827 || in_array(5237, $categories) || in_array(5688, $categories) || in_array(939, $categories) || in_array(946, $categories) || in_array(894, $categories)) { // If the product or its category match, allow the specified shipping method $allowed_shipping_methods[] = 'Gervais'; } elseif ($product_id == 38538 || $product_id == 38534) { $allowed_shipping_methods[] = 'La Poste (uniquement les batteries lithium ion)'; } elseif (in_array(5048, $categories) || in_array(5139, $categories) || in_array(5781, $categories) || $product_id == 40364) { // If the product or its category match, allow all shipping methods except "DHL" foreach ($rates as $rate_key => $rate) { if ($rate->method_id == 'dhl_shipping_method') { // Replace 'dhl_shipping_method' with the actual ID of the DHL shipping method unset($rates[$rate_key]); } } } } // Loop through the shipping rates and filter out the ones not allowed foreach ($rates as $rate_key => $rate) { if (!in_array($rate->method_id, $allowed_shipping_methods)) { unset($rates[$rate_key]); } } return $rates; } add_filter('woocommerce_package_rates', 'filter_shipping_methods', 20, 2);
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘woocommerce_package_rates not firing with plugin’ is closed to new replies.