Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set shipping method programmatically 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.

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.

like image 844
Tuesdave Avatar asked Sep 11 '15 01:09

Tuesdave


People also ask

How do I set shipping method in WooCommerce programmatically?

$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.


2 Answers

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.

like image 173
Anand Shah Avatar answered Sep 28 '22 08:09

Anand Shah


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

example:

WC()->session->set('chosen_shipping_methods', array( 'flat_rate:1' ) );
like image 40
Dhanraj Yadav Avatar answered Sep 28 '22 09:09

Dhanraj Yadav