WooCommerce 购物车中有捆绑产品时如何避免计算重复补贴?

问题描述 投票:0回答:1

使用下面的代码,我根据购物车物品运输类别和数量计算并显示补贴总额:

/**
 * Utility function: Get shipping class subsidy amount
 * 
 * @return float
 */
function get_shipping_class_subsidy_amount( $shipping_class ) {
    // return a float number for '12-50' case
    if ( false !== strpos($shipping_class, '12-50') ) {
        return 12.5;
    }
    // Extract the integer from the slug
    else {
        return preg_replace('/\D/', '',  $shipping_class);
    }
}

/**
 * Utility function: Get total subsidies amount
 * 
 * @return float
 */
function get_total_subsidies( $cart_items ){
    $total_subsidy = 0; // Initializing

    // Loop through cart items
    foreach ( $cart_items as $item ){
        $subsidy = (float) get_shipping_class_subsidy_amount( $item['data']->get_shipping_class() );
        $price = get_post_meta($values['product_id'] , '_price', true);
        if ( $subsidy > 0 ) {
            $total_subsidy += $item['quantity'] * $subsidy;
        }
    }
    return $total_subsidy;
}


/**
 * Display HTML formatted total subsidies amount in classic cart and checkout pages.
 * Hooked function.
 */
function display_total_subsidies() {
    if ( $total_subsidy = get_total_subsidies( WC()->cart->get_cart() ) ) {
        echo '<tr class="subsidies">
            <th>' . esc_html__( 'Subsidies', 'woocommerce' ) . '</th>
            <td data-title="' . esc_html__( 'Subsidies', 'woocommerce' ) . '">' . wc_price($total_subsidy) . '</td>
        </tr>';
    }
}

add_action ( 'woocommerce_cart_totals_before_shipping', 'display_total_subsidies', 10 ); // for Cart page
add_action ( 'woocommerce_review_order_before_shipping', 'display_total_subsidies', 10 ); // for Checkout page

问题在于,当它是捆绑产品时,购物车商品补贴金额会获得两倍,因为它考虑了捆绑产品本身及其产品组件。

但是标签上的计算是正确的。

php wordpress woocommerce bundle shipping-method
1个回答
0
投票

WC 中的捆绑产品被视为父捆绑及其各个组件的单独行项目,这意味着在

get_total_subsidies
函数的当前循环中可能会重复计算捆绑产品的补贴。

您可以尝试将补贴计算应用于代码中捆绑包的子组件。

function get_total_subsidies( $cart_items ){
    $total_subsidy = 0; // Initializing

    // Loop through cart items
    foreach ( $cart_items as $item_key => $item ){
        // Skip child items of bundled products
        if ( isset( $item['bundled_by'] ) && ! empty( $item['bundled_by'] ) ) {
            continue;
        }

        $subsidy = (float) get_shipping_class_subsidy_amount( $item['data']->get_shipping_class() );

        if ( $subsidy > 0 ) {
            $total_subsidy += $item['quantity'] * $subsidy;
        }
    }
    return $total_subsidy;
}
© www.soinside.com 2019 - 2024. All rights reserved.