Issue
I'm trying to write a specific function that allow to change automatically the product shipping class when a WooCommerce custom field is set with a specific value.
Please find below the screenshot about the custom fields
This is the code I had thought of but obviously it doesn't work.
function woo_on_product_save( $post_id ) {
$title = $product->get_meta( 'meta_easyfatt_libero_1' );
if ( $title = 'Trenta' ) {
$shipping_class_id = 1182;
}
$product = wc_get_product( $post_id );
$product->set_shipping_class_id( $shipping_class_id );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'woo_on_product_save', 100 );
Any suggestions would be greatly appreciated!
Solution
You have some minor mistakes
- You use
$product->get_meta(..
while$product
is not defined - The comparison operator in an if statement is
==
, not=
- Use
woocommerce_admin_process_product_object
to save instead of the outdatedwoocommerce_process_product_meta
hook
So you get:
// Save
function action_woocommerce_admin_process_product_object( $product ) {
// Get meta
$title = $product->get_meta( 'meta_easyfatt_libero_1' );
if ( $title == 'Trenta' ) {
// The targeted shipping class ID to be set for the product
$shipping_class_id = 1182;
// Set the shipping class ID
$product->set_shipping_class_id( $shipping_class_id );
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );
Answered By - 7uc1f3r
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.