PHP如何禁用基于小计的发货方式

ct3nt3jp  于 2023-02-18  发布在  PHP
关注(0)|答案(1)|浏览(119)

我试图禁用一些基于购物车小计(折扣后)航运方式。

// Disable Woocommerce shipping methods based on cart subtot

function wpsh_hide_shipping_based_on_subtotal( $rates, $package ) {
    // Retrieve cart subtotal
    //$cart_subtotal = $package['contents_cost'];
    $cart_subtotal = WC()->cart->get_cart_contents_total();
    
    // Shipping rate to be excluded
    $shipping_id1 = 'flat_rate:73';
    $shipping_id2 = 'flat_rate:75';
    $shipping_id3 = 'local_pickup:69';
    $shipping_id4 = 'flat_rate:76';
    $shipping_id5 = 'local_pickup:79';
 
    if ( $cart_subtotal < 99 ){
        unset( $rates[ $shipping_id4 ] ); 
        unset( $rates[ $shipping_id5 ] ); 
   }
    if ( $cart_subtotal >= 99 ){
        unset( $rates[ $shipping_id1 ] );   
        unset( $rates[ $shipping_id2 ] ); 
        unset( $rates[ $shipping_id3 ] );
   } 
        
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'wpsh_hide_shipping_based_on_subtotal', 10, 2 );

这似乎工作,但有时,特别是可变产品,它不隐藏低于99小计航运方式。我没有任何线索为什么。你能帮助我吗?

gjmwrych

gjmwrych1#

尝试使用woocommerce_shipping_packages隐藏配送方式。

add_filter( 'woocommerce_shipping_packages', array( $this, 'hide_shipping_rates_from_packages'), 10, 1 );
    
public function hide_shipping_rates_from_packages( $packags ) {
    if ( !empty( WC()->cart ) ) {
        $cart_subtotal = wc_format_decimal( WC()->cart->get_cart_subtotal( false ) ); // Without include compound taxes.
        if ( $cart_subtotal < 80 ) {
            foreach( $packags as $index => $package ) {
                unset($packags[$index]['rates']['free_shipping:1']);
            }
        }
     }
     return $packags;
}

对于重复购物车,请使用woocommerce_package_rates过滤器隐藏运输方式。此过滤器会影响会话存储的包裹详细信息,并且在此包裹的WC会话数据中存储费率时不会触发此过滤器。

add_filter( 'woocommerce_package_rates', array( $this, 'hide_shipping_rates_from_package_rates'), 10, 2 );
public function hide_shipping_rates_from_package_rates( $package_rates, $package ) {
    if ( !empty( WC()->cart ) ) {
        $cart_subtotal = wc_format_decimal( WC()->cart->get_cart_subtotal( false ) ); // Without include compound taxes.
        if ( $cart_subtotal < 80 ) {
            unset($packag_rates['free_shipping:1']);
        }
    }
    return $packag_rates;
}

相关问题