I am trying to update a custom meta on Woocommerce product update event. I’ve read that I should use woocommerce_update_product rather than save_post but I cannot figure out why only save_post works in my case.
Below code works
add_action( 'save_post', 'mp_sync_on_product_save', 20);
function mp_sync_on_product_save( $product_id ) {
update_post_meta($product_id, 'test_acf_product', "text");
};
Below code does not work
add_action( 'woocommerce_update_product', 'mp_sync_on_product_save', 20);
function mp_sync_on_product_save( $product_id ) {
update_post_meta($product_id, 'test_acf_product', "text");
};
I accidentally found that if I add exit;
at the end as below, the above code works (breaks page but meta saved in DB)
add_action( 'woocommerce_update_product', 'mp_sync_on_product_save', 20);
function mp_sync_on_product_save( $product_id ) {
update_post_meta($product_id, 'test_acf_product', "text");
exit;
};
I can get away with save_post but I’d love to know why woocommerce_update_product won’t work
I’d appreciate if anyone could give me some hint.
Thank you!
2
Answers
There are multiple ways to save product meta data when saving the product in backend:
1) Since WooCommerce 3 you can use:
2) Or the old WooCommerce way:
3) Or the WordPress way (targeting “product” custom post type):
4) Or also using
save_post
hook (and targeting “product” custom post type, to avoid this meta data to be saved for all posts types and custom post types):The answer from @loictheaztec is almost right. To save the data with CRUD you need to run the save_meta_data() command: