Monday, May 9, 2022

[FIXED] Which hook to save WooCommerce product meta in WooCommerce?

Issue

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!


Solution

There are multiple ways to save product meta data when saving the product in backend:

1) Since WooCommerce 3 you can use:

add_action( 'woocommerce_admin_process_product_object', 'action_save_product_meta' );
function action_save_product_meta( $product ) {
    $product->update_meta_data( 'test_acf_product', 'text' );
}

2) Or the old WooCommerce way:

add_action( 'woocommerce_process_product_meta', 'action_save_product_meta' );
function action_save_product_meta( $product_id ) {
    update_post_meta($product_id, 'test_acf_product', 'text' );
}

3) Or the Wordpress way (targeting "product" custom post type):

add_action( 'save_post_product', 'action_save_product_data', 20);
function action_save_product_data( $post_id ) {
     update_post_meta($post_id, 'test_acf_product', 'text');
}

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):

add_action( 'save_post', 'action_save_product_data', 20);
function action_save_product_data( $post_id ) {
    global $typenow;

    if ( 'product' === $typenow ) {
        update_post_meta($post_id, 'test_acf_product', 'text');
    }
}


Answered By - LoicTheAztec
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.