WooCommerce Notice,只运行一次


WooCommerce Notice, run only once

我对php相当陌生。在WooCommerce的Wordpress网站上工作。我添加了一个通知,显示"订单超过400美元可获得免费送货……",它可以工作,但当一个项目被删除或添加到购物车时,它会显示多次。我希望它只显示一次。下面是我的代码:

function sp_custom_notice() {
    if ( ! is_cart() ) {
        return;
    }
    $subtotal = WC()->cart->get_cart_subtotal();
    $free_shipping_threshold = 400;
    $notice_freeship = wc_add_notice( 'Get FREE shipping on orders over $400. Only valid in the US, not valid on bullets. <a href="https://bulletcentral.com/shipping/#promo">For more information, click here</a>', 'notice' );
    if ( $subtotal < $free_shipping_threshold ) {
        return $notice_freeship;
    }
}

使用sp_custom_notice函数添加哪个操作?如果使用

add_action('wp', 'sp_custom_notice')

它将被调用多次。

尝试连接其他动作:

add_action( 'woocommerce_before_checkout_form', 'sp_custom_notice' );

因此,该通知只在显示结帐页面时显示一次。

你可以做一件事。在执行操作时,删除以前的通知并显示新的通知。

function sp_custom_notice() {
if ( ! is_cart() ) {
    return;
}
$subtotal = WC()->cart->get_cart_subtotal();
$free_shipping_threshold = 400;
wc_clear_notices(); //Add this line
$notice_freeship = wc_add_notice( 'Get FREE shipping on orders over $400. Only valid in the US, not valid on bullets. <a href="https://bulletcentral.com/shipping/#promo">For more information, click here</a>', 'notice' );
if ( $subtotal < $free_shipping_threshold ) {
    return $notice_freeship;
}}