An online shop im working at uses 2 shipping methods: size based rates and local pickup.
The size based rates is the default shipping method, local pickup is only used when a customer clicks Click and pickup rather then Add to cart (internally, the product is added to the cart in both cases, but when using Click and pickup, extra cart item data is added to indicate this).
Calculating the total shipping cost when all cart items are reserved with Click and pickup is no problem, since you can filter the shipping rates at runtime with the filter woocommerce_package_rates
and change the shipping method so it will affect all cart items.
However, if the cart consists of items added with both Click and pickup and add to cart, it becomes more difficult to calculate the total shipping cost, because the shipping methods must be changed per cart item, and not affect all cart items.
Desired flow:
Cart items: 3
Book x 2 reserved with Click and pickup (cost: 0, local pickup shipping method)
Paper x 1 added to cart the normal way, (cost: default size rates, default shipping method)
Total shipping cost: local pickup cost + default shipping cost
Current code:
function cust_shipping_rates( $rates, $package ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$product_ids_with_local_pickup = array(); // 'click and pickup'
// Loop through line items
foreach( $package['contents'] as $line_item ) {
// Get product id
$product_id = $line_item['product_id'];
if ( $line_item['sofs_cap'] ) { // indication it's reserved with 'Click and pick'
array_push($product_ids_with_local_pickup, $product_id);
}
}
if ( count($product_ids_with_local_pickup) > 0 ) {
foreach ( $rates as $rate_key => $rate ) {
if ( in_array( $rate->method_id, array( 'bring_fraktguiden:5800' ) ) ) { // default shipping method
// how can i exclude the reserved products from being affected by this shipping method?
$rates[$rate_key]->set_cost(/* cost */); // changing this affects ALL items, not just the specific ones
}
}
}
return $rates;
}
add_filter('woocommmerce_package_rates', 'cust_shipping_rates', 999, 2);
woocommerce_cart_shipping_packages
hook, see this related threads and try to make yourself something. – LoicTheAztec