以编程方式设置运输方式 Woocommerce [英] Set shipping method programmatically Woocommerce
问题描述
我刚刚使用 custom_shipping
的 ID 创建了一个自定义的 Woocommerce 运输方式.该选项现在出现在 Woocommerce -> 设置 -> 运输管理页面上.
I just created a custom Woocommerce shipping method with the id of custom_shipping
. The option now appears on the Woocommerce -> Settings -> Shipping admin page.
我想根据用户的凭据动态设置送货方式.现在的默认方法是 flat_rate
.
I would like to set the shipping method dynamically based on a user's credentials. The default method is flat_rate
right now.
问题:我如何为满足要求的用户在整个会话期间将运输方式设置为 custom_shipping
?
Question:
How can I set the shipping method to custom_shipping
for users who meet a requirement, for the entirety of their session?
尝试过:
$chosen_methods = $woocommerce->session->set('chosen_shipping_methods', array('purolator_shipping');
这会在我的 cart
页面上正确设置会话变量chosen_shipping_methods",但是在移动到 checkout
时,会话将返回到使用 flat_rate代码> 运输方式.
This sets the session variable 'chosen_shipping_methods' correctly on my cart
page, but upon moving to checkout
, the session goes back to using the flat_rate
shipping method.
必须有一个钩子或过滤器,我可以插入它以在创建购物车会话或其他事情时更改运输方式.(当用户第一次将东西添加到购物车时).
There must be a hook or filter that I can plug into to change the shipping method upon cart-session creation or something. (When a user adds something to cart for first time).
我希望在加载其他任何东西之前设置新的运输方式,以便他们的购物车和结帐摘要中的运输方式看起来正确.
I would ideally like to set the new shipping method before anything else is loaded so the shipping method looks correct on their cart and checkout summaries.
感谢指导.
推荐答案
使用 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' ) );
}
顺便说一句,在购物车页面如果用户将送货方式从默认更改为其他方式,上面的代码会再次将其恢复为结帐页面上的默认方式,这会有点混乱为用户.
Just a note to say that, on the cart page if the user changes the shipping method from default to some other method, the code above will again revert it to the default method on the checkout page, which will be a bit confusing for the user.
这篇关于以编程方式设置运输方式 Woocommerce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!