Reputation: 12571
I am creating a Wordpress plugin that handles the shipping and delivery for WooCommerce.
I want to simply tell my WooCommerce cart (or order), this is what the shipping amount is.
I have tried directly setting WC()->cart->shipping_amount = $amount;
,
and also doing ->add_fee( $shippingServiceName, $amount );
in both cases the shipping_amount
on the cart remains at 0
.
How do I set the shipping amount?
Upvotes: 1
Views: 7257
Reputation: 12571
I ended up setting it directly on the order instead of on the cart;
Here is the method I created and used in my "complete purchase" processing :
function addShippingToOrder( $order, $shipping_amount, $shipping_name ) {
$shipping_tax = array();
$shipping_rate = new WC_Shipping_Rate( '', $shipping_name,
$shipping_amount, $shipping_tax,
'custom_shipping_method' );
$order->add_shipping($shipping_rate);
}
I also needed to save the shipping amount when I was in the cart logic, and then retrieve it when I was in the order logic, and I did that with a custom cart "session" variable :
WC()->session->set( 'my_custom_shipping_amount', $amt );
and
WC()->session->get( 'my_custom_shipping_amount' )
This is a very simple answer, but it took me the longest time to figure out - I even ended up creating a plugin especially for debugging changes to WC_Orders : WooCommerce Order Debugger Plugin
Upvotes: 7
Reputation: 1433
Try following code
add_filter('woocommerce_package_rates', 'apply_static_rate', 10, 2);
function apply_static_rate($rates, $package)
{
foreach($rates as $key => $value) {
$rates[$key]->cost = 150; // your amount
}
return $rates;
}
Upvotes: 1