Skip to content
Advertisement

Add random string to WooCommerce order items based on product SKU

I have set up variable products within WooCommerce.

Each variation has a unique SKU. My mission is to inspect the SKU within the cart, then according to the SKU, generate a number of random strings (16alphanumeric characters).

  • If item (1) in the cart is SKU ‘ABC’, then (x) number of unique strings are generated and stored for the respective order.

  • If item (2) in the cart is SKU ‘DEF’, then (y) number of unique strings are generated and stored for the respective order.

I have had a look at woocommerce_add_order_item_meta hook but I can’t seem to be able to access the item product data within the function I create associated with this hook?

I am now using

add_action( 'woocommerce_add_order_item_meta', 'experiment_add_order_item_meta', 10, 3 );
function experiment_add_order_item_meta( $item_id, $values, $cart_item_key  ) {
    // Get a product custom field value
    $custom_field_value = 'hithere';

    // Update order item meta
    if ( ! empty( $custom_field_value ) ){
        wc_add_order_item_meta( $item_id, 'meta_key1', $custom_field_value, false );
    }
}

But I am lost trying to get the product SKU from this point. I cannot var_dump() within the function to see the $values etc?

Advertisement

Answer

Explanation / functions used

So you get:

function generate_random_string( $length = 16 ) {
    return substr( str_shuffle( str_repeat( $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil( $length / strlen( $x ) ) ) ), 1, $length );
}
 
function action_woocommerce_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    // The WC_Product instance Object
    $product = $item->get_product();
    
    // Get product SKU
    $product_sku = $product->get_sku();
    
    // Generate random string
    $random_string = generate_random_string();
    
    // Compare
    if ( $product_sku == 'ABC' ) {
        $item->update_meta_data( '_random_string', $random_string );
    } elseif ( $product_sku == 'DEF' ) {
        $item->update_meta_data( '_random_string', $random_string );        
    } elseif ( $product_sku == 'GHI' ) {
        $item->update_meta_data( '_random_string', $random_string );        
    } else {
        $item->update_meta_data( '_random_string', $random_string );
    }   
}
add_action( 'woocommerce_checkout_create_order_line_item', 'action_woocommerce_checkout_create_order_line_item', 10, 4 );
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement