更改 Woocommerce 中的默认运输方式

May*_*pta 1 php wordpress cart woocommerce shipping-method

我有两种运输方式。第一个是免费送货,第二个是我收取额外费用的快递运费统一运费。默认情况下,在购物车中选择快递运输,这会导致一些买家感到困惑,因为我不提供免费送货服务。

是否可以将默认选择的方法更改为免费送货?

Loi*_*tec 6

我认为您只需要为每个送货区域重新排序送货方式,将“免费送货”放在第一行。

如果它不起作用,您可以添加以下代码:

add_action( 'woocommerce_before_cart', 'auto_select_free_shipping_by_default' );
function auto_select_free_shipping_by_default() {
    if ( isset(WC()->session) && ! WC()->session->has_session() )
        WC()->session->set_customer_session_cookie( true );

    // Check if "free shipping" is already set
    if ( strpos( WC()->session->get('chosen_shipping_methods')[0], 'free_shipping' ) !== false )
        return;

    // Loop through shipping methods
    foreach( WC()->session->get('shipping_for_package_0')['rates'] as $key => $rate ){
        if( $rate->method_id === 'free_shipping' ){
            // Set "Free shipping" method
            WC()->session->set( 'chosen_shipping_methods', array($rate->id) );
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。测试和工作。

如果您不使用购物车页面并且有重定向到结帐,则必须在代码woocommerce_before_cart中用woocommerce_before_checkout_form钩子替换。