根据Woocommerce中购物车项目的运输类别计数更改运输类别

时间:2018-09-14 08:46:19

标签: php wordpress woocommerce cart shipping-method

我无法使用默认的WooCommerce运送类别设置。我们有一个小型网上商店,有2运费。一种用于邮箱中适合的产品,另一种用于不适合邮箱的产品。

我们要进行以下设置:如果有2种具有邮箱运输类别的产品,那么该价格将成为包裹价格。

现在默认情况下,WooCommerce只收取邮箱传送等级的1倍。

2 个答案:

答案 0 :(得分:2)

首先,您需要按照以下屏幕中的说明进行运输设置,以“固定费率”运输方式和仅一个名为“邮箱”的运输类别(为“邮箱”或“无运输类别”设置所需的金额)

enter image description here

  

因此,您的某些产品将具有“邮箱”运输类别,而其他所有产品将没有运输类别。没有运输类别(无运输类别)的产品将成为您的“包装”。

如果“邮箱”运输类别中有多个项目,则以下代码将删除购物车项目的运输类别:

// Updating cart item price
add_action( 'woocommerce_before_calculate_totals', 'change_change_shipping_class', 30, 1 );
function change_change_shipping_class( $cart ) {
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE define your shipping class SLUG
    $mailbox_shipping_class = 'mailbox';

    $mailbox_count = 0;

    // 1st cart item Loop: Counting "mailbox" shipping classes cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Set the new price
        if( $cart_item['data']->get_shipping_class() == $mailbox_shipping_class ) {
            $mailbox_count += $cart_item['quantity'];
        }
    }

    // If there is more than one item we continue
    if( $mailbox_count <= 1 )
        return; // Exit

    // 2nd cart item Loop: Reset the cart items with shipping class "mailbox"
    foreach ( $cart->get_cart() as $cart_item ) {
        if(  $cart_item['data']->get_shipping_class() == $mailbox_shipping_class ){
            $cart_item['data']->set_shipping_class_id('0');
        }
    }
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。

答案 1 :(得分:0)

感谢代码,效果很好!

我使用了另一个运输类别ID,而不是0。通过检查您可以在其中输入费率的页面代码获取ID。 (它说name =“ woocommerce_flat_rate_class_cost_58”,所以id是58。)这是我的“大包裹”类。这样,它可以正确导出到我的邮件/标签插件。

相关问题