Skip to content

Instantly share code, notes, and snippets.

@WPprodigy
Created February 6, 2017 18:34
Show Gist options
  • Save WPprodigy/1b7c47a90e363e5f9c1b3d024e1a91ab to your computer and use it in GitHub Desktop.
Save WPprodigy/1b7c47a90e363e5f9c1b3d024e1a91ab to your computer and use it in GitHub Desktop.
Add costs to a WooCommerce shipping rate in a pattern
function wc_ninja_change_shipping_rate_cost( $rates, $package ) {
$shipping_method_id = 'table_rate:14:1';
$cost_per_case = 50;
$products_per_case = 12;
// Make sure the specific table rate is available
if ( isset( $rates[$shipping_method_id] ) ) {
$products_in_cart = WC()->cart->cart_contents_count;
$additional_cost = 0;
if ( $products_in_cart > $products_per_case ) {
// Calculate costs of extra cases
$extra_cases_in_cart = floor( ($products_in_cart - $products_per_case) / $products_per_case );
if ( $extra_cases_in_cart ) {
(int)$additional_cost = ($extra_cases_in_cart * $cost_per_case) + $additional_cost;
}
// Calculate the remaining single bottle prices
$single_bottles_left = $products_in_cart % $products_per_case;
if ( $single_bottles_left ) {
(int)$additional_cost = (wc_ninja_single_bottle_costs( $single_bottles_left )) + $additional_cost;
}
// Add our additional cost to the shipping method
if ( $additional_cost ) {
$rates[$shipping_method_id]->cost = $rates[$shipping_method_id]->cost + $additional_cost;
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'wc_ninja_change_shipping_rate_cost', 10, 2 );
function wc_ninja_single_bottle_costs( $number = 1 ) {
switch ( $number ) {
case 1:
$cost = 22;
break;
case 2:
$cost = 23;
break;
case 3:
case 4:
$cost = 25;
break;
default:
$cost = 26;
break;
}
return $cost;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment