Skip to content

Instantly share code, notes, and snippets.

@forsvunnet
Last active May 28, 2022 13:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save forsvunnet/61265563a1cabaad6502b349988e8540 to your computer and use it in GitHub Desktop.
Save forsvunnet/61265563a1cabaad6502b349988e8540 to your computer and use it in GitHub Desktop.
Bring weight filter
<?php
/**
* Filter the bring shipping rates.
* Sets the price of the chosen services based on weight
*/
add_filter( 'bring_shipping_rates', function( $rates ) {
// Configure services and prices.
$services = [ 'SERVICEPAKKE', '5800' ];
$prices = [
'1kg' => 199,
'5kg' => 299,
'10kg' => 399,
];
// Calculate the weight of items in cart.
$total_weight = 0;
$items = WC()->cart->get_cart();
foreach ( $items as $item ) {
if ( ! $item['data']->needs_shipping() ) {
continue;
}
$total_weight += $item['data']->get_weight() * $item['quantity'];
}
// Convert the total weight to grams.
$total_weight = wc_get_weight( $total_weight, 'g' );
// Calculate the price for the current weight.
$price = false;
foreach ( $prices as $threshold => $cost ) {
// Find the value and weight unit.
if ( ! preg_match( '/^(\d+)\s*(kg|g|lbs|oz)$/', $threshold, $matches ) ) {
continue;
}
$weight_unit = $matches[2];
$weight = wc_get_weight( $matches[1], 'g', $weight_unit );
if ( $total_weight > $weight ) {
$price = $cost;
}
}
// Return early if the total weight is less than the lowest price threshold.
if ( false === $price ) {
return $rates;
}
// Set the price for the chosen services.
foreach ( $rates as &$rate ) {
if ( in_array( $rate['bring_product'], $services ) ) {
$rate['cost'] = $price;
}
}
return $rates;
}, 999 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment