且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WooCommerce中特定运输类别的购物车消息

更新时间:2023-11-30 12:38:40

在您的情况下,您似乎已经在自己的商品中定义了运输类别ID 问题代码,因此您需要使用 WC_Product get_shipping_class_id()方法,如下所示:

In your case it seems that you have defined a shipping class Id in your question code, so you need to use the WC_Product get_shipping_class_id() method instead as follow:

add_action( 'woocommerce_before_calculate_totals', 'cart_items_shipping_class_message', 20, 1 );
function cart_items_shipping_class_message( $cart ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $shipping_class_id = '150'; // Your shipping class Id

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        // Check cart items for specific shipping class, displaying a notice
        if( $cart_item['data']->get_shipping_class_id() == $shipping_class_id ){
            wc_clear_notices();
            wc_add_notice( sprintf(
                __('Beers can only be shipped via %s. To reveal much cheaper UPS Shipping Rates, remove Beers from the Cart.', 'woocommerce'),
                '<a title="Pallet Shipping" href="/shipping-delivery/#Pallet_Shipping" target="_blank" rel="noopener noreferrer">' . __("Pallet Shipping", "woocommerce") . '</a>'
            ), 'notice' );
            break;
        }
    }
}

代码进入活动目录的functions.php文件子主题(或活动主题)。

Code goes in functions.php file of your active child theme (or active theme). It should work.

添加::要仅在购物车页面上显示通知,请替换以下代码:

Addition: To display the notice only on cart page, replace the following code:

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

通过以下方式:

    if ( ! is_cart() || ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
        return;