Created
January 1, 2024 13:43
-
-
Save damiencarbery/67f65344c1919eda718ca0a6d43e56c7 to your computer and use it in GitHub Desktop.
Hide shipping rates if free shipping available - Hide non-free shipping rates if zero cost shipping rates are available. https://www.damiencarbery.com/2024/01/hide-shipping-rates-if-free-shipping-available/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Hide shipping rates if free shipping available | |
Plugin URI: https://www.damiencarbery.com/2024/01/hide-shipping-rates-if-free-shipping-available/ | |
Description: Hide non-free shipping rates if zero cost shipping rates are available. | |
Author: Damien Carbery | |
Version: 0.1 | |
WC tested up to: 8.4.0 | |
*/ | |
defined( 'ABSPATH' ) || exit; | |
// Inspired by: https://www.businessbloomer.com/woocommerce-hide-shipping-options-free-shipping-available/ | |
class HideNonFreeRatesWhenFreeAvailable { | |
// Initialize any plugin variables. | |
public function __construct() { | |
$this->init(); | |
} | |
// Set up WordPress specfic actions. | |
private function init() { | |
add_filter( 'woocommerce_package_rates', array( $this, 'unset_non_zero_shipping_when_free_ones_available' ), 9999, 2 ); | |
} | |
// Hide non-zero rates when free ones available. | |
// The free ones can be Free Shipping, Local Pickup or even Flat Rate, as long as the cost is zero. | |
public function unset_non_zero_shipping_when_free_ones_available( $rates, $package ) { | |
$all_free_rates = array(); | |
foreach ( $rates as $rate_id => $rate ) { | |
if ( $rate->get_cost() == 0 ) { | |
$all_free_rates[ $rate_id ] = $rate; | |
} | |
} | |
// If no free rates available then return the passed rates unmodified. | |
if ( empty( $all_free_rates )) { | |
return $rates; | |
} else { | |
// If free ones found then return them. | |
return $all_free_rates; | |
} | |
} | |
} | |
$HideNonFreeRatesWhenFreeAvailable = new HideNonFreeRatesWhenFreeAvailable(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment