Mahbubur Rahman

Thoughts and Writings

20 Feb 2017
How to create unique SKU with WP User Frontend custom field.

The unique SKU of the products is not being set when the products are created. To add unique SKU with products, then follow the instructions given below.

1) Add a custom text field with _sku to the product form.

Screenshot:
http://prntscr.com/eb2ext

2) Add the following code inside the theme’s functions.php file.

Note: This is a Developer level doc. If you are unfamiliar with code/templates and resolving potential conflicts, contact me for assistance.
function wpuf_unique_product_sku_notice( $error ) {
    if ( isset( $_POST['_sku'] ) ) {
        global $wpdb;

        $sku = $_POST['_sku'];

        $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );

        if ( $product_id ) {
            return __( 'SKU is not unique, you must enter unique SKU' );
        }
    }

    return '';
}

add_filter( 'wpuf_update_post_validate', 'wpuf_unique_product_sku_notice' );
add_filter( 'wpuf_add_post_validate', 'wpuf_unique_product_sku_notice' );

3) Now, try to submit a product using the frontend product form. Use an existing SKU related to other product. You will see the following error.

Screenshot:

All done.

Leave a Comment

Your email address will not be published. Required fields are marked *