首页 > 解决方案 > 使用 Woocommerce 中的运输类删除重复的运输包裹

问题描述

我网站中的产品由 2 个运输插件之一处理: WooCommerce 的Printful IntegrationWooCommerce Shipping 的 Printify。当每个运输插件有混合项目时。当有混合项目(这是一个冲突和一个问题)时,这些插件将每个运输包分成两部分。

因此,我在Printful 插件处理的产品中添加了一个运输类(id 是,并尝试通过@LoicTheAzec(欢呼)调整woocommerce 应答代码中特定运输类的隐藏运输方法,仅删除运输由于运输插件之间的冲突,来自具有 id 2 和 3 的特定重复运输包裹的方法...</p> 'printful' 548

在此处输入图像描述

这是我的实际代码:

    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 个运输包裹而不是两个:

在此处输入图像描述

任何帮助表示赞赏。

标签: phpwordpresswoocommercecartshipping-method

解决方案


这里的问题与您的两个运输插件之间的拆分包裹冲突有关,当混合物品在购物车中时。在这种情况下,每个插件都会拆分运输包,这会添加 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 文件中。当购物车物品混合时,它应该可以工作并且只显示两个运输包裹。


推荐阅读