Require an Image, SKU and Price Before Publishing Products
Keeps a product as a draft, with a notice explaining what is missing, when someone tries to publish it without a featured image, SKU or price.
Opens WPIDE on
Code
$wpide_publish_requires = array( 'image', 'sku', 'price' ); // Checks to run.
add_action( 'woocommerce_admin_process_product_object', function ( $product ) use ( $wpide_publish_requires ) {
if ( 'publish' !== $product->get_status() ) {
return;
}
$missing = array();
// phpcs:disable WordPress.Security.NonceVerification -- WooCommerce verifies the product save nonce.
if ( in_array( 'image', $wpide_publish_requires, true ) && ! $product->get_image_id() && empty( $_POST['_thumbnail_id'] ) ) {
$missing[] = 'a featured image';
}
// phpcs:enable
if ( in_array( 'sku', $wpide_publish_requires, true ) && '' === (string) $product->get_sku() ) {
$missing[] = 'a SKU';
}
if ( in_array( 'price', $wpide_publish_requires, true ) && ! $product->is_type( array( 'variable', 'grouped', 'external' ) ) && '' === (string) $product->get_regular_price() ) {
$missing[] = 'a regular price';
}
if ( in_array( 'price', $wpide_publish_requires, true ) && $product->is_type( 'variable' ) && ! $product->get_variation_price( 'max' ) ) {
$missing[] = 'a priced variation';
}
if ( $missing ) {
$product->set_status( 'draft' );
set_transient( 'wpide_publish_blocked_' . get_current_user_id(), $missing, 60 );
}
}, 99 );
add_action( 'admin_notices', function () {
$missing = get_transient( 'wpide_publish_blocked_' . get_current_user_id() );
if ( $missing ) {
delete_transient( 'wpide_publish_blocked_' . get_current_user_id() );
printf( '<div class="notice notice-error"><p>%s</p></div>', esc_html( 'The product was saved as a draft because it is missing ' . implode( ', ', $missing ) . '. Add them and publish again.' ) );
}
} );
Notes
Remove checks you do not need from $wpide_publish_requires; variable products need at least one priced variation.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.