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.
I would like to set the shipping method dynamically based on a user's credentials. The default method is flat_rate
right now.
Question:
How can I set the shipping method to custom_shipping
for users who meet a requirement, for the entirety of their session?
Tried:
$chosen_methods = $woocommerce->session->set('chosen_shipping_methods', array('purolator_shipping');
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.
Guidance appreciated.
$chosen_methods = $woocommerce->session->set('chosen_shipping_methods', array('purolator_shipping'); 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.
Use the woocommerce_before_checkout_shipping_form
hook
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.
// WC()->session->set('chosen_shipping_methods', array( 'your_shipping_rate_id_here' ) );
example:
WC()->session->set('chosen_shipping_methods', array( 'flat_rate:1' ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With