首页 > 解决方案 > 根据 WooCommerce 上的总订单价值在购物车上显示消息

问题描述

我正在尝试根据总订单价值在购物车上显示一条通知:(每花费 28.50 欧元,客户将向医院捐赠 1 件产品)

这是我到目前为止所做的(没有成功)

  function wc_donation_message() {


// Get some variables
$cart_total     = (float) WC()->cart->total; // Total cart amount

// Conditional messages
if ( $cart_total >= 28.50 ) {
    wc_add_notice( sprintf(
        __("Thank you! You just donated 1 meal", "woocommerce"), // Text message
        )
}
if ( $cart_total >= 57 ) {
    wc_add_notice( sprintf(
        __("Thank you! You just donated 2 meals", "woocommerce"), // Text message
        )
}

}

标签: phpfunctionwoocommerce

解决方案


这是解决方案(根据评论更新)

// show a notice in the cart based on the total amount
add_action( 'woocommerce_before_cart', 'boozers_count_cart_bottles' );
function boozers_count_cart_bottles() {
    // gets the total of the cart
    $total = WC()->cart->total;
    // set the step
    $step = 28.5;
    // calculate the number of meals
    $meals = floor( $total / $step );

    // show a different message if "$meals" is less than 1
    if ( $meals < 1 ) {
        wc_print_notice( 'Thank you! Your order contributed to our solidarity initiative.', 'notice' );
        return;
    }

    if ( $meals > 1 ) {
        $text = 'meals';
    } else {
        $text = 'meal';
    }
    // show the notice in the cart
    wc_print_notice( sprintf( __( 'Thank you! You just donated %u %s.' ), $meals, $text ), 'notice' );
}

此时将显示消息:

在此处输入图像描述

该代码已经过测试并且可以工作。将其添加到活动主题的 functions.php 文件中。


推荐阅读