woocommerce hide shipping methods conditionally on number

时间:2019-03-19 15:08:59

标签: php wordpress woocommerce cart shipping-method

If there are more than 15 articles in a cart. How can I force just one desired shipping method (i.e. DHL) and hide all other shipping methods?

I already have the plugin "flexible shipping" but prefer a hook in functions.php.

1 个答案:

答案 0 :(得分:0)

如果购物车中有15件以上,以下将仅启用一种定义的运输方式:

add_filter( 'woocommerce_package_rates', 'hide_shipping_methods_based_on_item_count', 10, 2 );
function hide_shipping_methods_based_on_item_count( $rates, $package ) {
    // HERE the targeted shipping method ID (see the attribute "value" of the related shipping method input field)
    $targeted_method_id = 'flat_rate:12'; // <== Replace with your DHL shipping method ID

    // HERE the articles count threshold
    $more_than = 15;

    // Cart items count
    $item_count = WC()->cart->get_cart_contents_count();
    if( WC()->cart->get_cart_contents_count() > $more_than ) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( $rate->id != $targeted_method_id ) {
                unset($rates[$rate_key]);
            }
        }
    }

    return $rates;
}

代码在活动子主题(或主题)的function.php文件中。经过测试,可以正常工作。

  

刷新运输缓存: (必需)

     
      
  1. 此代码已保存在活动主题的function.php文件中。
  2.   
  3. 购物车是空的
  4.   
  5. 在运输区域设置中,禁用/保存任何运输方式,然后启用“后退” /保存。
  6.   
     

您已完成,并且可以对其进行测试。