以编程方式设置运输方式 Woocommerce

Tue*_*ave 6 php wordpress woocommerce

我刚刚创建了一个自定义的 Woocommerce 运输方式,ID 为custom_shipping. 该选项现在出现在 Woocommerce -> 设置 -> 运输管理页面上。

我想根据用户的凭据动态设置运输方式。默认方法是flat_rate现在。

问题: 如何custom_shipping为满足要求的用户在整个会话期间设置送货方式?

尝试:

$chosen_methods = $woocommerce->session->set('chosen_shipping_methods', array('purolator_shipping');
Run Code Online (Sandbox Code Playgroud)

这在我的cart页面上正确设置了会话变量 'chosen_shipping_methods' ,但在移动到 时checkout,会话将返回到使用flat_rate运输方式。

必须有一个钩子或过滤器,我可以插入它以在创建购物车会话或其他事情时更改运输方式。(当用户第一次将东西添加到购物车时)。

理想情况下,我想在加载其他任何东西之前设置新的运输方式,以便他们的购物车和结帐摘要中的运输方式看起来正确。

指导表示赞赏。

Ana*_*hah 6

使用woocommerce_before_checkout_shipping_form钩子

add_action( 'woocommerce_before_checkout_shipping_form', 'before_shipping');

function before_shipping( $checkout ) {

    // check the user credentials here and if the condition is met set the shipping method

    WC()->session->set('chosen_shipping_methods', array( 'purolator_shipping' ) );

}
Run Code Online (Sandbox Code Playgroud)

只是要说明一下,在购物车页面上,如果用户将送货方式从默认更改为其他方式,上面的代码将再次将其恢复为结帐页面上的默认方式,这对用户来说会有点混乱.