Skip to content
Advertisement

Make SKU mandatory in Woocommerce before publishing a product

I would like to know if there is any way to make the SKU field required, before publishing a new product. Otherwise, if there is no SKU, to be able to save the product only as a draft.

Advertisement

Answer

Maybe you can simply use this very simple code snippet to display an error message when the SKU field is empty when trying to save a the product (works for products and variations too).

If the product with an empty SKU is published, it will be saved as “DRAFT”.

The code:

add_action('woocommerce_admin_process_product_object', 'mandatory_product_sku');
add_action('woocommerce_admin_process_variation_object', 'mandatory_product_sku');
function mandatory_product_sku( $product ) {
    if( ! $product->get_sku( 'edit' ) ) {
        $message = __( 'Caution! The SKU field is required.', 'woocommerce' );
        
        if( $product->get_status('edit') === 'publish' ) {
            $product->set_status('draft');
            $message .= ' ' . __('Product has been saved as "DRAFT".', 'woocommerce' );
        }
        WC_Admin_Meta_Boxes::add_error( $message );
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement