Skip to content

Instantly share code, notes, and snippets.

@twoelevenjay
Last active May 31, 2016 22:12
Show Gist options
  • Save twoelevenjay/98a24b8cefaeb164c7eaceeb042d64cd to your computer and use it in GitHub Desktop.
Save twoelevenjay/98a24b8cefaeb164c7eaceeb042d64cd to your computer and use it in GitHub Desktop.
<?php
/*
* Conditionally hide shipping methid, based
* on shipping class found in the cart
*/
function is_shipping_class_in_cart( $shipping_class ) {
$is_shipping_class_in_cart = false;
// loop through all items in the cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = $values['data'];
$terms = get_the_terms( $product->id, 'product_shipping_class' );
if ( $terms ) {
foreach ( $terms as $term ) {
// check if items shipping class matches $shipping_class
$product_shipping_class = $term->slug;
if ( $shipping_class === $product_shipping_class ) {
$is_shipping_class_in_cart = true;
}
}
}
}
return $is_shipping_class_in_cart;
}
add_filter( 'woocommerce_package_rates', 'conditionally_unset_a_shipping_method', 10, 2 );
function conditionally_unset_a_shipping_method( $rates, $package ) {
// Use the method id of shipping gateway to conditionally hide. You can find the method id
// under WooCommerce > Settings > Shipping > Shipping Methods under the ID column.
$method_id_to_unset = 'usps';
// use the slug of shipping class to check for in the cart.
$shipping_class_to_detect = 'no-usps';
if ( is_shipping_class_in_cart( $shipping_class_to_detect ) ) {
foreach ( $rates as $rate ) {
if ( $rate->method_id == $method_id_to_unset ) {
unset( $rates[$rate->id] );
}
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment