Generate unique SKU for each product (Custom code)

Question

On my site, I’m generating SKU’s (unique ids) for each product. I don’t use Whoocomerce, instead I have post type product for a different purpose. I’m using this function below to generate the ID’s and I would like to know, whether this I a good way. For now, the function seems to work fine.

/*
generate unique sku
*/

function generate_sku($length = 10)
{
    global $current_user;
    wp_get_current_user();

    //$first_try
    $first_try = strtoupper(substr(str_shuffle(md5(time())),0,$length));

    $args = array
    (
        'post_type'       => 'product',
        'posts_per_page'  => '-1',
        'author'          => $current_user->ID,
        'meta_query' => array(
            array(
                    'key'     => 'sku',
                    'value'   => $first_try,
                    'compare' => 'LIKE'
            )
        ),
    );

    $loop = new WP_Query( $args );
    if ( $loop->have_posts() )
    {
        $sku = generate_sku();
    }
    else
    {
        $sku = $first_try;
    }


    return $sku;
}
0
Game Unity 7 months 0 Answers 95 views 0

Leave an answer