Free shipping message
<?php
function get_free_shipping_minimum($zone_name = 'Nederland')
{
if (! isset($zone_name)) {
return null;
}
$result = null;
$zone = null;
$zones = \WC_Shipping_Zones::get_zones();
foreach ($zones as $z) {
if ($z['zone_name'] == $zone_name) {
$zone = $z;
}
}
if ($zone) {
$shipping_methods_nl = $zone['shipping_methods'];
$free_shipping_method = null;
foreach ($shipping_methods_nl as $method) {
if ($method->id == 'free_shipping') {
$free_shipping_method = $method;
break;
}
}
if ($free_shipping_method) {
$result = $free_shipping_method->min_amount;
}
}
return $result;
}
function get_free_shipping_cost() {
$shipping_packages = WC()->cart->get_shipping_packages();
$shipping_zone = wc_get_shipping_zone(reset($shipping_packages));
$zone_name = $shipping_zone->get_zone_name();
return (float) get_free_shipping_minimum($zone_name);
}
function s7_get_shipping_classes() {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$classes = [];
foreach($items as $item) {
$classes[] = $item['data']->get_shipping_class();
}
return $classes;
}
function s7_is_free_class_active($classes) {
if(count($classes) == 1 && $classes[0] == 'gratis') {
return true;
}
return false;
}
add_action('woocommerce_cart_totals_before_shipping', function () {
$free_shipping_cost = get_free_shipping_cost();
$subtotal = WC()->cart->total;
$price_from = $free_shipping_cost;
if (!s7_is_free_class_active(s7_get_shipping_classes()) && $free_shipping_cost > ($subtotal + 250)) {
$remaining = $free_shipping_cost - $subtotal;
$notice = sprintf("Bestel voor nog %s en je bestelling wordt gratis verzonden.", wc_price($remaining));
ob_start(); ?>
<tr class="bg-secondary-lighter">
<td colspan="2"><?= $notice ?></td>
</tr>
<?php
$content = ob_get_clean();
echo $content;
}
});
function free_shipping_notice() {
if ( ! is_cart() && ! is_checkout() ) {
return;
}
$packages = WC()->cart->get_shipping_packages();
$package = reset( $packages );
$zone = wc_get_shipping_zone( $package );
$cart_total = WC()->cart->get_displayed_subtotal();
if ( WC()->cart->display_prices_including_tax() ) {
$cart_total = round( $cart_total - ( WC()->cart->get_discount_total() + WC()->cart->get_discount_tax() ), wc_get_price_decimals() );
} else {
$cart_total = round( $cart_total - WC()->cart->get_discount_total(), wc_get_price_decimals() );
}
foreach ( $zone->get_shipping_methods( true ) as $k => $method ) {
$min_amount = $method->get_option( 'min_amount' );
if ( $method->id == 'free_shipping' && ! empty( $min_amount ) && $cart_total < $min_amount ) {
$remaining = $min_amount - $cart_total;
wc_add_notice( sprintf(__('Bestel nog voor %s, dan is de verzending gratis.', 'ceramicnature'), wc_price( $remaining )) );
}
}
}
add_action('woocommerce_before_cart', __NAMESPACE__ . '\\free_shipping_notice');