Skip to content

Instantly share code, notes, and snippets.

@coenjacobs
Created April 14, 2013 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coenjacobs/5384488 to your computer and use it in GitHub Desktop.
Save coenjacobs/5384488 to your computer and use it in GitHub Desktop.
Disables specific shipping methods if there are products with one or more specified shipping classes in the cart.
<?php
/*
Plugin Name: WC Disable Shipping for Classes
Description: Disables specific shipping methods if there are products with one or more specified shipping classes in the cart.
Author: Coen Jacobs
Author URI: http://coenjacobs.me
Version: 1.0
*/
add_filter( 'woocommerce_available_shipping_methods', 'wcdsfc_shipping_method_filter' );
/**
* Filters the array storing all available shipping methods on checkout
*
* Removes some of them if products match specified shipping classes
*
* @param array $available_methods Contains the available shipping methods
*/
function wcdsfc_shipping_method_filter( $available_methods ) {
global $woocommerce;
// Define the shipping classes that need to cause the disabling of
// specific shipping methods if in cart. Key is the slug of the
// shipping class, where the value of the array contains an array
// with all the shipping methods it needs to disable when one or
// more products match the key shipping class.
$check_shipping_classes = array(
'heavy' => array( 'free_shipping' ),
);
if ( ! empty( $woocommerce->cart->cart_contents ) ) {
// Cart is not empty, now loop through the cart and check for the shipping classes defined above
foreach ( $woocommerce->cart->cart_contents as $product ) {
foreach ( array_keys( $check_shipping_classes ) as $shipping_class ) {
if ( has_term( $shipping_class, 'product_shipping_class', $product['product_id'] ) ) {
// Loop through the shipping methods that need to be disabled, and do so if they are available now
foreach ( $check_shipping_classes[ $shipping_class ] as $shipping_method ) {
if ( isset( $available_methods[ $shipping_method ] ) ) {
unset( $available_methods[ $shipping_method ] );
}
}
}
}
}
}
return $available_methods;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment