Skip to content

Instantly share code, notes, and snippets.

Created February 23, 2015 13:44
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 anonymous/c947e54622d208939c72 to your computer and use it in GitHub Desktop.
Save anonymous/c947e54622d208939c72 to your computer and use it in GitHub Desktop.
WooCommerce: Ship One Category of Products to Certain States
<?php
/**
* Plugin Name: WooCommerce Only Ship to Continental US
* Plugin URI: https://gist.github.com/BFTrick/7805588
* Description: Only Ship to the Continental US
* Author: Patrick Rauland
* Author URI: http://patrickrauland.com/
* Version: 1.0.1
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
* @author Patrick Rauland
* @since 1.0.1
*/
/**
* Only ship to the continental US
*
* @param array $available_methods
*/
function patricks_only_ship_to_continental_us( $available_methods ) {
global $woocommerce;
// List states excluded
$excluded_states = array( 'AL','AK','AZ','AR','CA','CO','CT','DC','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MI','MN','MS','MO','MT','NE','NV','NJ','NM','NY','NC','ND','OH','OK','OR','PA','PR','RI','SC','SD','TN','TX','UT','VT','VA','VI','WA','WV','WI','WY' );
// start of the loop that fetches the cart items
foreach ( $woocommerce-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product-&gt;id, 'product_cat' );
// second level loop search, in case some items have several categories
foreach ($terms as $term) {
$_categoryid = $term-&gt;term_id;
}
if (( $_categoryid === 33 )) {
//category is in cart!
$product_in_cart = true;
}
}
if( in_array( $woocommerce-&gt;customer-&gt;get_shipping_state(), $excluded_states ) &amp;&amp; ($product_in_cart === true) ) {
// Empty the $available_methods array
$available_methods = array();
}
return $available_methods;
}
add_filter( 'woocommerce_package_rates', 'patricks_only_ship_to_continental_us', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment