0

I am using a plugin where I can import products into WooCommerce. The SKU field is not filled in during this process. I cannot find a way to programmatically set the SKU after an item is imported. I have tried many things, and I was sure the code below would work. I could use some help if anyone has an idea of where I am going wrong.

add_action('updated_post_meta', 'my_updated_post_meta', 10, 4);
add_action('added_post_meta', 'my_updated_post_meta', 10, 4);
function my_updated_post_meta($meta_id, $post_id, $meta_key, $meta_value) {
    if ($meta_key == '_mySku') {
        if (get_post_type($post_id) == 'product') {
            update_post_meta($post_id,'_sku',$meta_value);
        }
    }
}
1

You should use save_post hook. Try the code below:

function wpse_304031_save_post( $post_id, $post ) {

    // return if autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    $your_sku = 'Custom SKU for ' . $post->post_title;

    if( $post->post_type == 'product' ) {
        if( empty( get_post_meta( $post_id, '_sku', true ) ) ) {
            update_post_meta( $post_id, '_sku', $your_sku );
        }
    }

}

add_action( 'save_post', 'wpse_304031_save_post' );

Here I'm using title of the product to build sku. You can use anything you want.

| improve this answer | |
  • This causes a white screen / critical error – Sean Doherty Mar 5 at 11:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.