Skip to content

Instantly share code, notes, and snippets.

@braddalton
Last active October 30, 2025 09:04
Show Gist options
  • Save braddalton/61892db0acfe3d10de301f9bf8b37928 to your computer and use it in GitHub Desktop.
Save braddalton/61892db0acfe3d10de301f9bf8b37928 to your computer and use it in GitHub Desktop.
Swap out the product ID 6455 on line 3 of the code to match your free shipping product. Full Tutorial https://wpsites.net/free-tutorials/free-shipping-per-product-woocommerce/
add_filter( 'woocommerce_package_rates', 'wpsites_show_only_free_shipping_for_specific_product', 20, 2 );
function wpsites_show_only_free_shipping_for_specific_product( $rates, $package ) {
$target_product_id = 6455; // 🔹 Replace with your product ID
$product_in_cart = false;
// Check if the target product is in the cart
foreach ( $package['contents'] as $item ) {
if ( $item['product_id'] == $target_product_id ) {
$product_in_cart = true;
break;
}
}
// If the product is in the cart → remove all shipping methods except free shipping
if ( $product_in_cart ) {
$free_shipping_available = false;
// Keep only free shipping if it already exists
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' !== $rate->method_id ) {
unset( $rates[$rate_id] );
} else {
$free_shipping_available = true;
}
}
// If no free shipping method exists in the zone, create one dynamically
if ( ! $free_shipping_available ) {
$rates = array();
$rates['custom_free_shipping'] = new WC_Shipping_Rate(
'custom_free_shipping',
__( 'Free shipping', 'woocommerce' ),
0,
array(),
'custom_free_shipping'
);
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment