FamousWolluf
FamousWolluf

Reputation: 578

Woocommerce - Get shipping costs on the product page

I'm using Wordpress 3.9.14.

I use the flat_rate method for my shipping costs.
It contains a default cost_per_order and I use 2 shipping_classes inside flat_rate for additional costs for some products.

I want to show the shipping costs on the product page.
Right now I use the $product->shipping_class_id() to get the ID but I can't figure out how to get the costs for this shipping_class_id.
Because if I know the costs I can add this to the cost_per_order to calculate the total shipping costs for the product.

I also can't figure out how to get the cost_per_order value.

If there is no solution at all, I can use as an emergency solution a switch/case statement and put the costs in there but then I need to change the code when I change the flat_rate costs, so I don't prefer this kind of solutions.

Upvotes: 5

Views: 24438

Answers (2)

Vlad T.
Vlad T.

Reputation: 1

I did it in woocommerce/checkout/review-order.php for my needs. So i think you can use it anywhere...

$product = wc_get_product($cart_item['product_id']);

// just to know what we have
$shipping_class_id = $product->get_shipping_class_id();
$shipping_class = $product->get_shipping_class();

// name of shipping class if you need
$shipping_class_term = get_term( $shipping_class_id, 'product_shipping_class' );
echo $shipping_class_term->name;

// and here IF we know $instance_id (is shipping method id in shipping zone admin page) 
$instance_id = 12; // who knows how to get it with code - welcome
$flat_rate = new WC_Shipping_Flat_Rate($instance_id);
$symbol = get_woocommerce_currency_symbol();

echo $symbol.$flat_rate->instance_settings['class_cost_'.$shipping_class_id]);

Hope this helps someone. or there is better way?

Upvotes: -1

FamousWolluf
FamousWolluf

Reputation: 578

I have figured it out:

$shipping_class_id = $product->get_shipping_class_id();
$shipping_class= $product->get_shipping_class();
$fee = 0;

if ($shipping_class_id) {
   $flat_rates = get_option("woocommerce_flat_rates");
   $fee = $flat_rates[$shipping_class]['cost'];
}

$flat_rate_settings = get_option("woocommerce_flat_rate_settings");
echo 'Shipping cost: ' . ($flat_rate_settings['cost_per_order'] + $fee);

Upvotes: 5

Related Questions