Woocommerce:在购物车更新上运行PHP函数

我想在我的WooCommerce购物车页面上显示一条消息,告诉客户他们需要购买多少才能获得免费礼物。

我已经获得了下面的代码,但是有一个问题。

当客户更新购物车或数量时,以下代码不会更新(因为页面不会重新加载)。

    <?php $e_cart = WC()->cart->cart_contents_total * 1.25;?>
    <?php $e_cart_remaining = 300 - $e_cart; ?>

    <?php
        if ( $e_cart < 300 ) {
            echo "Get a free gift,when you purchase for ${e_cart_remaining} more.";
        }?>

问题是,如果客户的购物车中有250个商品,则消息将显示:“购买50个以上即可获得免费礼物”。 (因为您将获得300的免费礼物)。但是,如果他们更改一种产品的数量,文本仍显示为50。(因为页面尚未更新

每次购物车更新后,如何触发此脚本或代码块?

非常感谢您。

vip58581658 回答:Woocommerce:在购物车更新上运行PHP函数

要根据购物车金额在购物车页面上显示自定义消息,请使用以下命令:

// On cart page only
add_action( 'woocommerce_check_cart_items','custom_total_item_quantity_message' );
function custom_total_item_quantity_message() {
  $e_cart = WC()->cart->cart_contents_total * 1.25;
  $e_cart_remaining = 300 - $e_cart; 

    if( is_cart() &&  $e_cart < 300  ){
        wc_print_notice( sprintf( __("Get a free gift,when you purchase for %s more.","woocommerce"),$e_cart_remaining ),'notice' );
    }
}

代码进入您的活动子主题(或活动主题)的function.php文件中。

本文链接:https://www.f2er.com/3166085.html

大家都在问