为 WooCommerce 中销售的产品启用免费送货

Enable free shipping for products on sale in WooCommerce

在 WooCommerce 中,是否可以自动对任何打折产品应用免费送货?

每个月我们都有不同的促销产品,所有促销产品自动符合免运费条件。对于销售产品,我目前必须手动将运费 class 更改为“免运费”,然后在销售结束后改回“标准运费”。我想自动执行此操作,以便任何正在销售的产品自动符合免运费订单的条件。

我可以为每个产品 ID 申请免费送货,但我一直无法弄清楚如何将此应用于促销产品。

function wcs_my_free_shipping( $is_available ) {
    global $woocommerce;
 
    // set the product ids that are eligible
    $eligible = array( '360' );
 
    // get cart contents
    $cart_items = $woocommerce->cart->get_cart();

    // loop through the items looking for one in the eligible array
    foreach ( $cart_items as $key => $item ) {
        if( in_array( $item['product_id'], $eligible ) ) {
            return true;
        }
    }
 
    // nothing found return the default value
    return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'wcs_my_free_shipping', 20 );

要提供免费送货服务,您可以使用 is_on_sale();

function filter_woocommerce_shipping_free_shipping_is_available( $is_available, $package, $shipping_method ) {  
    // Loop through cart items
    foreach( $package['contents'] as $cart_item ) {
        // On sale
        if ( $cart_item['data']->is_on_sale() ) {
            // True
            $is_available = true;
            
            // Notice
            $notice = __( 'free shipping', 'woocommerce' );
            
            // Break loop
            break;
        }
    }
    
    // Display notice
    if ( isset( $notice ) ) {
        wc_add_notice( $notice, 'notice' );
    }
 
    // Return
    return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'filter_woocommerce_shipping_free_shipping_is_available', 10, 3 );

可选:可免费送货时隐藏其他送货方式

function filter_woocommerce_package_rates( $rates, $package ) {
    // Empty array
    $free = array();

    // Loop trough
    foreach ( $rates as $rate_id => $rate ) {
        if ( $rate->method_id === 'free_shipping' ) {
            $free[ $rate_id ] = $rate;
            
            // Break loop
            break;
        }
    }
    
    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );