I need to update the SKU of a WooCommerce product but nothing I tried works.
I’m trying to update the SKU of a product. I build a new select custom field (´´id=>’_leadlovers_integration_product’´´ on the code below) on the inventory settings with options I import by API from another plataform). This works fine. I can save the code, print it. But I can´t simply make the update of the SKU with this code.
I’ve tried a lot of snipets but nothing works…
add_action( 'woocommerce_process_product_meta', 'save_leadlovers_custom_fields');
function save_leadlovers_custom_fields( $post_id )
{
//These two guys works perfectly
update_post_meta( $post_id, '_leadlovers_integration_check', esc_attr( $_POST['_leadlovers_integration_check'] ) );
update_post_meta( $post_id, '_leadlovers_integration_product', esc_attr( $_POST['_leadlovers_integration_product'] ) );
//First, I tried this... no success
//update_post_meta( $post_id, '_sku', esc_attr( $_POST['_leadlovers_integration_product'] ) );
//Then I tried this, with no changes, forcing by hand the
//update_post_meta( $post_id, '_sku', '30445' );
//I tried using the function set_sku() too... nothing happens
//$product = wc_get_product( $post_id );
//$product->set_sku( get_post_meta( $post->ID, '_leadlovers_integration_product', true ) );
//nothing too with this...
$product = wc_get_product( $post_id );
$product->set_sku( '30445' ) ;
///i tried even make the procedure on other function...
}
Well, someone have an idea what happens, or… not happens??
Thanks,
3
Answers
Thanks @Akin and @mujuonly...
I tried first to set up the priority to 50 and using
$product->set_sku()
but, so, we need to use$product->save
together... only to save didn't work.Them, I tried to use update_post_meta with priority seted to 50 and just works...
Thanks
update_post_meta
should actually work fine. You should still use this lastsave
function for the other set_sku function. In that:If that doesn’t work either, there’s a problem with your
woocommerce_process_product_meta
hook or it’s not working for the time you want it to.EDIT
Or this I’m guessing. You might actually be using a hook too early to save meta. So you are saving something but again _sku is saved again right after your function. So you should try a different hook to make sure it works at the right time. It would be nice if you could provide more details so that I can assist you.
EDIT 2
I reviewed it again maybe the hook should work. Can you delay the runtime by trying this?
This hook runs just before saving a product to the database. This hook specific for changing any product data just before saving.