在 Woocommerce 中使用运输 class 删除重复的运输包裹

Remove duplicated shipping packages using a shipping class in Woocommerce

我网站上的产品由这 2 个运输插件之一处理:Printful Integration for WooCommerce and Printify for WooCommerce Shipping。当每个运输插件中有混合物品时。当有混合物品时,这些插件将每个运输包裹一分为二(这是一个冲突和问题)

所以我加了一个运费class'printful'(id是548 ) 到由 @LoicTheAzec 的 Printful plugin, and tried to adjust 答案代码处理的产品(干杯),仅从具有 id 2 和 3 的特定重复运输包裹中删除运输方式由于运输插件之间的冲突…

这是我的实际代码:

    add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class to find
    $class = 548; //CAMDEN HARBOR CHART MUG is in shipping class

    // HERE define the shipping methods you want to hide
    $method_key_ids = array('printify_shipping_s', 'printify_shipping_e');

    // Checking in cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        // If we find the shipping class
        if( $cart_item['data']->get_shipping_class_id() == $class ){
            foreach( $method_key_ids as $method_key_id ){

                unset($rates[$method_key_id]); // Remove the targeted methods
            }
            break; // Stop the loop
        }
    }
    return $rates;
}

但它不起作用,我仍然收到 4 个包裹,而不是两个:

感谢任何帮助。

这里的问题与当混合项目在购物车中时两个运输插件之间的拆分包冲突有关。在那种情况下,每个插件拆分运输包,添加 4 个拆分包而不是 2 个。

这些插件正在使用 woocommerce_cart_shipping_packages 拆分具有未知优先级 (so I will set a very high priority) 的运输包裹。

以下代码将保留购物车中的前 2 个拆分包裹(以及结帐):

add_filter( 'woocommerce_cart_shipping_packages', 'remove_split_packages_based_on_items_shipping_class', 100000, 1 );
function remove_split_packages_based_on_items_shipping_class( $packages ) {
    $has_printful = $has_printify = false; // Initializing

    // Lopp through cart items
    foreach( WC()->cart->get_cart() as $item ){
        // Check items for shipping class "printful"
        if( $item['data']->get_shipping_class() === 'printful' ){
            $has_printful = true;
        } else {
            $has_printify = true;
        }
    }

    // When cart items are mixed (using both shipping plugins)
    if( $has_printful && $has_printify ){
        // Loop through split shipping packages
        foreach( $packages as $key => $package ) {
            // Keeping only the 2 first split shipping packages
            if( $key >= 2 ){
                // Removing other split shipping packages
                unset($packages[$key]);
            }
        }
    }

    return $packages;
}

代码进入您的活动子主题(活动主题)的 function.php 文件。当购物车商品混装时,它应该可以正常工作并仅显示两个运输包裹。