1
votes

I have a function that is generating a unique string. This is currently working. However it is running for all products that are sold at checkout. I would like the following function to only run if a specific product is in the order Items.

Here is what I have so far:

add_action( 'woocommerce_order_status_processing', 'add_unique_id' );

function add_unique_id($order_id) {
    $order = new WC_Order( $order_id );
    $items = $order->get_items(); 
    foreach ($items as $item_id => $product ) {
        $str = "";
        $length= 45;
$characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
$max = count($characters) - 1;
    for ($i = 0; $i < $length; $i++) {
    $rand = mt_rand(0, $max);
    $str .= $characters[$rand];
    }
      wc_add_order_item_meta($item_id, 'Member Number', $str);
    }
}
1

1 Answers

0
votes

Updated (for product category)

This function is not working in cart or Checkout, but after submission when order has been generated.

I have changed your code a little bit to allow this generation code only for a defined product ID or a product category (that you will need to set inside the function):

add_action( 'woocommerce_order_status_processing', 'add_unique_id', 10, 1 );
function add_unique_id( $order_id ) {
    $order = wc_get_order( $order_id );
    foreach ($order->get_items() as $item_id => $item_obj ) {

        // HERE set YOUR targeted product ID
        $targeted_product_id = 0; // 0 value make it work only for product category (below)

        // HERE set YOUR product category (ID, slug or nameā€¦ Or an array of values)
        $category = 'memberships'; 

        // If the targeted product ID or the product category is found in the order items.
        if( $item_obj->get_product_id() == $targeted_product_id || has_term( $category,'product_cat', $item_obj->get_product_id() ) ) {

            $str = "";
            $length= 45;
            $characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
            $max = count($characters) - 1;
            for ($i = 0; $i < $length; $i++) {
                $rand = mt_rand(0, $max);
                $str .= $characters[$rand];
            }
            wc_add_order_item_meta( $item_id, 'Member Number', $str );
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works for WooCommerce version 3+

So your unique "Member number" will be generated only for order items that are matching with the targeted product ID or the product category.