【问题标题】:Run functions automatically when the shopping cart is updated in WooCommerce?在 WooCommerce 中更新购物车时自动运行功能?
【发布时间】:2019-05-15 00:53:56
【问题描述】:

我的 WooCommerce 子主题 functions.php 文件中有以下函数。 但是每次更新购物车时,我都需要重新加载购物车页面才能运行功能。

如何在购物车更新时自动执行功能?

<?php
add_action( 'woocommerce_before_calculate_totals', 'add_custom_weight', 10, 1 );
function add_custom_weight( $cart ) {

    if (($_SESSION["kilo_rate"]) && ($_SESSION["cart_items_count"]) > 0 ){

    $each_cart_item_weight = ($_SESSION["kilo_rate"]/$_SESSION["cart_items_count"]);
    foreach ( WC()->cart->get_cart() as $cart_item ) {
     //very simplified example - every item in cart will be 100 kg
    $cart_item['data']->set_weight( $each_cart_item_weight );
    }

    }
    // print_r( $cart->get_cart_contents_weight() ); // Only for testing (not on checkout page)
}

add_action('woocommerce_cart_contents_weight', 'set_cart_contents_weight');
function set_cart_contents_weight( $weight ) {        
    $weight = $_SESSION["kilo_rate"];    
    return $weight;     
}

add_action('woocommerce_cart_collaterals', 'myprefix_cart_extra_info');
function myprefix_cart_extra_info() {

    echo '<div class="cart-extra-info">';
    echo '<h2>Delivery Information</h2>';
    echo '<p>Weight: '. $_SESSION["kilo_rate"].'Kg (Pallet plus Products)';
    echo '</br> Items in Cart: '.$_SESSION["cart_items_count"];
    echo '</br> Pallet Size - Length '.$_SESSION["max_length_cart"].'m Width '.$_SESSION["max_width_cart"].'m</p>';
    echo '</div>';

}



//Add Warehouse Handling Fee
add_action( 'woocommerce_cart_calculate_fees','woocommerce_warehouse_picking_charge' );
function woocommerce_warehouse_picking_charge() {
  global $woocommerce;
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

        $handling_fee = $_SESSION["cart_less_samples"] * 20;
        $woocommerce->cart->add_fee( 'Warehouse Handling Fee', $handling_fee, true, '' );
}

?>

【问题讨论】:

  • 我认为您从一开始就没有使用正确的方法,您应该在有关$_SESSION["kilo_rate"]$_SESSION["cart_items_count"] 的问题中提供更多背景信息...

标签: php ajax wordpress woocommerce


【解决方案1】:

感谢各位cmets,非常感谢。

$_SESSION["kilo_rate"] 来自另一个函数,该函数根据装载到托盘上的产品的实际体积计算运输重量率。 它与购物车中产品的实际重量无关。

我正在使用基于重量的运输插件https://wordpress.org/plugins/weight-based-shipping-for-woocommerce/,它似乎使用购物车中的所有物品(而不是购物车总重量)来计算运费。

解决此问题的唯一方法是更改​​购物车中每件商品的重量,这就是为什么我将 $_SESSION["kilo_rate"] 除以购物车中的商品数量 $_SESSION["cart_items_count" ]

我希望这是有道理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多