Ad
Per Product Flat Rate Shipping WooCommerce
I'd like to do per product shipping programmatically. And I don't want to use the plugin. This seems like it would easy:
- add meta field called "shipping_price" for each product.
- hook into checkout and update shipping based off each products "shipping_price" that's in your cart
I know how to do #1. but any ideas on the best way to achieve #2?
Ad
Answer
This can be done in the following way, using get_post_meta
to get the meta field 'shipping_price'
Note 1: to test this code added a line with dummy data
Note 2: Don't forget to specify the $rate->method_id
function filter_woocommerce_package_rates( $rates, $package ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Set variable
$cost = 0;
// Loop through line items
foreach( $package['contents'] as $line_item ) {
// Get product id
$product_id = $line_item['product_id'];
// Quantity
$quantity = $line_item['quantity'];
// Get post meta
$shipping_price = get_post_meta( $product_id, 'shipping_price', true);
// DEBUG, for testing purposes, REMOVE AFTERWARDS!!
$shipping_price = 10;
if ( $shipping_price ) {
$cost += $shipping_price * $quantity;
}
}
if ( $cost > 0 ) {
// (Multiple)
foreach ( $rates as $rate_key => $rate ) {
// Targeting
if ( in_array( $rate->method_id, array( 'free_shipping', 'distance_rate', 'table_rate' ) ) ) {
// Set rate cost
$rates[$rate_key]->cost = $cost;
}
}
// Single
// Set rate cost
// $rates['free_shipping']->cost = $cost;
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 100, 2 );
Ad
source: stackoverflow.com
Related Questions
- → How can I change what to be indexed on google by using WooCommerce?
- → Woocommerce SEO -- Noindex 'Order by' archive
- → Change WooCommerce product category title?
- → Achieving flat URL structure with woocommerce for SEO
- → Customize meta tag of SEO Yoast
- → Woocommerce custom Product slug
- → can we import products from woocommerce to shopify with csv file?
- → button Onclick function with document.getElementById
- → Get an element of a struct array by attribute value in a Golang template
- → WooCommerce tabs not working in Divi theme
- → Linkwise Affiliate integration in Woocommerce thankyou page
- → Getting header info through php://input
- → Trying to change the style in "Select an Option" dropdown of Woocommerce checkout
Ad