Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save isaumya/c76d21f1d75eee77fee18698b239ac63 to your computer and use it in GitHub Desktop.
Save isaumya/c76d21f1d75eee77fee18698b239ac63 to your computer and use it in GitHub Desktop.
Enable or Disable Free Shipping or Flat Rate Shipping Based On WooCommerce Product

Let's say you have a product for which you just want to show the Free Shipping option or the Flat Rate shipping option, you can easuly do it using the following filters.

Hide The Flat Rate SHipping Option For Certain WooCommerce Product

add_filter( 'woocommerce_shipping_flat_rate_is_available', function( $is_available ) {
	// set the product ids that are eligible
	$eligible = array( '1711' );

	// get cart contents
	$cart_items = WC()->cart->get_cart();

	// loop through the items looking for one in the eligible array
	foreach ( $cart_items as $key => $item ) {
		if( in_array( $item['product_id'], $eligible ) ) {
			return false; // disabling flat rate shipping
		}
	}

	// nothing found return the default value
	return $is_available;
} );

Enable Free Shipping for Certain WooCommerce Product

add_filter( 'woocommerce_shipping_free_shipping_is_available', function( $is_available ) {
	// set the product ids that are eligible
	$eligible = array( '1711' );
 
	// get cart contents
	$cart_items = WC()->cart->get_cart();

	// loop through the items looking for one in the eligible array
	foreach ( $cart_items as $key => $item ) {
		if( in_array( $item['product_id'], $eligible ) ) {
			return true;
		}
	}
 
	// nothing found return the default value
	return $is_available;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment