Good Day, I have been trying to figure out how to select shipping class programmatically using php. I'm creating a woocommerce product from frontend using a form and on form submission the product is created but i can get to make any of the shipping class to be selected. below is the screenshot showing the shipping class setup on the product created from frontend with the inspect element tab showing the ids (as value) of the shipping classes
i'm using the below code to select the phone Shipping Fee Class
$pShipping_Class = 25; //Where 25 is the id/value for Phone Shipping Fee Class
update_post_meta( $product_id, 'product_shipping_class', $pShipping_Class );
The update_post_meta works for every other field even the custom dropdown field i created i was able to use update_post_meta( $product_id, '_list_of_stores', 'custom-order' );
to select the value custom-order from the custom dropdown field i created but when i tried same thing for the shipping class, it doesn't work. Not sure what i'm doing wrong.
Please point me in the right direction. how can i update the shipping class using php. i already have the IDs and slug.
Thanks
UPDATE: I realized that when i manually select the Phone Shipping Fee and hit the Update product button. it added selected property (i.e selected="selected" ), see screenshot below;
Please how to i make this update/select any of the shipping class (either by IDs or slug), as the shipping class need to be updated on the fly to give users the shipping rate of the product they created and added to cart.
Shipping classes are not managed by post meta data for the products. They are managed by a custom taxonomy, so you can't use
update_post_meta()
function.
In Woocommerce, shipping classes are managed by the custom taxonomy product_shipping_class
and you will need to use wp_set_post_terms() function to make it work programmatically like:
$shipping_class_id = 25; // the targeted shipping class ID to be set for the product
// Set the shipping class for the product
wp_set_post_terms( $product_id, array($shipping_class_id), 'product_shipping_class' );
Or since Woocommerce 3, you could use the WC_Product
CRUD method set_shipping_class_id()
this way:
$shipping_class_id = 25; // the targeted shipping class ID to be set for the product
$product = wc_get_product( $product_id ); // Get an instance of the WC_Product Object
$product->set_shipping_class_id( $shipping_class_id ); // Set the shipping class ID
$product->save(); // Save the product data to database