微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为Woocommerce中的待售产品启用免费送货

如何解决为Woocommerce中的待售产品启用免费送货

在WooCommerce中,是否可以将免费送货自动应用于任何正在销售的产品?

每个月我们都有不同的产品在销售,所有销售的产品都会自动获得免费送货的资格。对于销售产品,我目前必须手动将运输类别更改为“免费运输”,然后在销售结束后重新更改为“标准运输”。我想使它自动化,因此任何在售的产品都会自动使该订单具有免费送货的条件。

我可以针对每个产品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',2 );

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。