【发布时间】:2017-04-05 04:05:23
【问题描述】:
如果购物车中有特定产品,我想添加免费送货。如果它是购物车中唯一的物品,我有一种方法可以工作,但是一旦我将其他东西添加到购物车中,它就不起作用。该产品包含航运类包邮。 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 );
【问题讨论】:
标签: php wordpress woocommerce shipping