Manually assigning a shipping class to each product can be tedious and time-consuming. Here’s where default product shipping classes come to the rescue!
This code tutorial will show you how to set a default shipping class for your products in WooCommerce without the need to access the “edit product” WordPress admin page to pick an option from the shipping class dropdown.
Enjoy!
PHP Snippet: Programmatically Set The Shipping Class For All WooCommerce Products
Note: you will need to know the shipping class ID before using the code below. There are two ways to find the shipping class ID in WooCommerce:
1. WooCommerce Settings
- This method only works if you have already created the shipping class.
- Go to WooCommerce > Settings > Shipping > Shipping Classes.
- You’ll see a list of your shipping classes with their names and slugs. However, the ID won’t be displayed directly on this page.
- Use your browser “inspect” tool as described here https://www.businessbloomer.com/woocommerce-disable-free-shipping-if-cart-has-shipping-class/#woocommerce-how-to-find-shipping-class-id to retrieve the ID.
2. Edit Product Page
- This method involves using your browser’s developer tools once again.
- Open the Edit Product page for any product.
- Locate the Product data meta box and navigate to the Shipping tab.
- Right-click on the Shipping class dropdown element and select Inspect (or Inspect Element).
- In the developer tools window, look for the value attribute associated with the selected shipping class option. This value is the shipping class ID.
/**
* @snippet Default Shipping Class @ Woo Products
* @tutorial Get CustomizeWoo.com FREE
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 8
* @community Join https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_product_get_shipping_class_id', 'bbloomer_default_product_shipping_class', 9999, 2 );
function bbloomer_default_product_shipping_class( $value, $product ) {
$value = $value ? $value : 44; // default to shipping class ID = 44
return $value;
}
Hi Rodolfo! Could you please clarify on this? Does this code replace the “No Shipping Class” in the cart with the chosen shipping class?
I initially thought that it would set the default Shipping Class on the products to a specific one so that all products that were unassigned would be automatically assigned the Class I wanted. It doesn’t seem to do that and it also doesn’t seem to change the Default Shipping Class for new products created either.
Thank you
Hey Kat! This will not change the “display” i.e. the select dropdown chosen option. Instead, it will “set” the shipping class to whatever shipping class ID you wish, whenever it’s needed e.g. on the Cart page. Does this help?