Woocommerce如果运送类在购物车中,所有购物车商品免运费

时间:2017-04-05 04:05:24

标签: php wordpress woocommerce shipping

如果特定商品在购物车中,我想添加免费送货服务。我有一个方法,如果它是购物车中唯一的项目,但只要我在购物车中添加其他东西后它就不起作用。该产品包含运费类免运费。 tl; dr即使我将其他商品添加到购物车,我该怎样才能使用它。

来源:https://www.speakinginbytes.com/2014/12/enable-free-shipping-per-product/

某类课程免费送货

if ( ! class_exists( 'WC_Enable_Free_Shipping' ) ) :
class WC_Enable_Free_Shipping {
    protected static $instance = null;
    private function __construct() {
        // add our check
        add_filter( 'woocommerce_shipping_free_shipping_is_available', array( $this, 'patricks_enable_free_shipping' ), 20 );
    }
    /**
     * Enable free shipping for orders with products that have the free-shipping shipping class slug
     */
    public function patricks_enable_free_shipping( $is_available ) {
        global $woocommerce;
        // set the shipping classes that are eligible
        $eligible = array( 'free-shipping' );
        // get cart contents
        $cart_items = $woocommerce->cart->get_cart();
        // loop through the items checking to make sure they all have the right class
        foreach ( $cart_items as $key => $item ) {
            if ( ! in_array( $item['data']->get_shipping_class(), $eligible ) ) {
                // this item doesn't have the right class. return default availability
                return $is_available;
            }
        }
        // nothing out of the ordinary return true
        return true;
    }
    /**
     * Return an instance of this class.
     */
    public static function get_instance() {
        // If the single instance hasn't been set, set it now.
        if ( null == self::$instance ) {
            self::$instance = new self;
        }
        return self::$instance;
    }
}
add_action( 'init', array( 'WC_Enable_Free_Shipping', 'get_instance' ), 0 );
endif;

如果有免费送货,请隐藏其他送货方式

function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

1 个答案:

答案 0 :(得分:0)

你可以试试“woocommerce_available_shipping_method”钩子。这段代码可以帮助你:

add_filter( 'woocommerce_available_shipping_methods', 'custom_shipping_methods' );
function custom_shipping_methods( $available_methods ) { 

    // Check your cart product's logic here
    foreach ( WC()->cart->cart_contents AS $item ) { 

        // If something in cart then just keep free shipping in available method
        // That logic goes here
    }

    // return available methods
    return $available_methods;
}