.
WORDPRESS PLUGINS ABOUT

Hiding a Shipping option for certain products or categories

2 minute read, 1 if you're quick

Sometimes you might need to hide one or more shipping option(s) for a particular product or category. This code will do this, all you need to do is add it to your themes Functions.php file.

In this example, I am hiding the shipping option called "Free Shipping". You can get this from the database table called "woocommerce_shipping_zone_methods".
The category ID I am using is 390 which is the parent category ID, you will find this in the table "terms".

/**
 * Hide Free Shipping for certain products only.
 * The category ID of 390 is the main category I would like to hide the shipping for. Check all categories with the parent of 390.
 * woocommerce_package_rates will only fire when something has changed in the basket. Use the Debug option in WooCommerce Shipping settings to test.
 *
 */
add_filter( 'woocommerce_package_rates', 'hide_free_Shipping', 10, 2 );
function hide_free_Shipping( $rates, $package ) {

	/**
	 * Set the shipping methods to be removed (like "fat_rate:5").
	 *
	 */
    $method_instances_ids = array('free_shipping:1'); 

    $found = false;

	/**
	 * Loop through cart items checking for products with category parent of 390.
	 *
	 */
    if ( $package ) foreach( $package['contents'] as $cart_item ) {
		
		$cat = wp_get_post_terms($cart_item['product_id'], 'product_cat');
		
		if ( $cat ) foreach ( $cat as $v ) {
			
			if ( $v->parent == '390' ) {

				$found = true;
				break;
			}
			
		}
		unset( $cat );
		
    }

	/**
	 * If not found exit.
	 *
	 */	
    if ( ! $found ) return $rates;

	/**
	 * Loop through your active shipping methods.
	 *
	 */
    foreach( $rates as $rate_id => $rate ) {

		/**
		 * Remove shipping method.
		 *
		 */	
        if ( in_array( $rate_id, $method_instances_ids ) ){
			
            unset( $rates[$rate_id] );
			
        }
		
    }    
    return $rates;
	
}

Something to remember, the filter "woocommerce_package_rates" will only run when the basket products have changed. You can use the Debug option in the WooCommerce Shipping settings to test it out.

^