我刚刚创建了一个id为custom_shipping
的自定义Woocommerce发货方法。该选项现在出现在Woocommerce ->设置-> Shipping管理页面上。
我想根据用户的凭据动态设置送货方法。目前默认的方法是flat_rate
。
问题:我如何为满足要求的用户设置运输方法为custom_shipping
,为他们的整个会话?
尝试:
$chosen_methods = $woocommerce->session->set('chosen_shipping_methods', array('purolator_shipping');
在我的cart
页面上正确设置会话变量'chosen_shipping_methods',但在移动到checkout
时,会话返回使用flat_rate
运输方法。
必须有一个钩子或过滤器,我可以插入到更改运输方法在购物车会话创建或其他东西。(当用户第一次向购物车中添加商品时)。
理想情况下,我希望在加载任何其他内容之前设置新的送货方法,以便送货方法在他们的购物车和结帐摘要上看起来正确。
指导感激。
使用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' ) );
}
需要说明的是,在购物车页面上,如果用户将送货方法从默认方法更改为其他方法,则上面的代码将再次将其恢复为结帐页面上的默认方法,这将使用户感到有点困惑。
// WC()->session->set('chosen_shipping_methods', array( 'your_shipping_rate_id_here' ) );
的例子:
WC()->session->set('chosen_shipping_methods', array( 'flat_rate:1' ) );