Require a Featured Image Before Publishing
Stops posts from being published or scheduled until a featured image is set, in both the block editor and the classic editor.
Opens WPIDE on
Code
// Post types that must have a featured image before they go live.
$wpide_require_image_types = array( 'post' );
foreach ( $wpide_require_image_types as $wpide_image_type ) {
// Block editor (REST API) saves.
add_filter( "rest_pre_insert_{$wpide_image_type}", function ( $prepared, $request ) {
if ( false !== strpos( (string) $request->get_route(), '/autosaves' ) ) {
return $prepared;
}
$status = isset( $prepared->post_status ) ? $prepared->post_status : get_post_status( (int) $request['id'] );
if ( ! in_array( $status, array( 'publish', 'future' ), true ) ) {
return $prepared;
}
if ( isset( $request['featured_media'] ) ) {
$image = (int) $request['featured_media'];
} else {
$image = ! empty( $request['id'] ) ? (int) get_post_thumbnail_id( (int) $request['id'] ) : 0;
}
if ( $image > 0 ) {
return $prepared;
}
return new WP_Error( 'wpide_featured_image_required', 'Please set a featured image before publishing.', array( 'status' => 400 ) );
}, 10, 2 );
}
// Classic editor saves: keep the post as a draft and explain why.
add_filter( 'wp_insert_post_data', function ( $data, $postarr ) use ( $wpide_require_image_types ) {
if ( ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || empty( $postarr['ID'] ) || ! isset( $_POST['action'] ) || 'editpost' !== $_POST['action'] ) {
return $data;
}
if ( ! in_array( $data['post_type'], $wpide_require_image_types, true ) || ! in_array( $data['post_status'], array( 'publish', 'future' ), true ) ) {
return $data;
}
$image = isset( $_POST['_thumbnail_id'] ) ? (int) $_POST['_thumbnail_id'] : (int) get_post_thumbnail_id( (int) $postarr['ID'] );
if ( $image > 0 ) {
return $data;
}
$data['post_status'] = 'draft';
add_filter( 'redirect_post_location', function ( $location ) {
return add_query_arg( 'wpide_needs_image', 1, remove_query_arg( 'message', $location ) );
} );
return $data;
}, 10, 2 );
add_action( 'admin_notices', function () {
if ( isset( $_GET['wpide_needs_image'] ) ) {
echo '<div class="notice notice-error"><p>The post was saved as a draft. Please set a featured image before publishing.</p></div>';
}
} );
Notes
Already published posts without an image also need one before they can be updated.
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.