How To Require a Featured Image Before You Can Publish a Post

Are you looking for a way to require a featured image before you can publish a post? This snippet will require that you have added a featured image before your post can be published. If you try to publish a post without a featured image after adding this snippet, you will receive this message: “You must select Featured Image. Your Post is saved but it can not be published.”

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');
 
function wpds_check_thumbnail($post_id) {
 
// change to any custom post type 
if(get_post_type($post_id) != 'post')
return;
 
if ( !has_post_thumbnail( $post_id ) ) {
// set a transient to show the users an admin message
set_transient( "has_post_thumbnail", "no" );
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'wpds_check_thumbnail');
// update the post set it to draft
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
 
add_action('save_post', 'wpds_check_thumbnail');
} else {
delete_transient( "has_post_thumbnail" );
}
}
 
function wpds_thumbnail_error()
{
// check if the transient is set, and display the error message
if ( get_transient( "has_post_thumbnail" ) == "no" ) {
echo "<div id='message' class='error'><p><strong>You must select Featured Image. Your Post is saved but it can not be published.</strong></p></div>";
delete_transient( "has_post_thumbnail" );
}
 
}

https://www.isitwp.com/require-featured-image-can-publish-post/

«
»
ACF (3)
Admin Column (4)
Breadcrumbs (2)
CSS (6)
Custom post types (4)
Custom Taxonomies (3)
Customizer (4)
Hooks & Filters (3)
Jquery (9)
LAMP (10)
Login (5)
Meta boxes (6)
Multisite (2)
My Code (1)
Open Graph Meta Tags (1)
Redirects (2)
SEO (4)
Theme Building (5)
Title Tags (2)
Typography (3)
Uncategorised (54)
User Roles & Capabilities (2)
White labeling (9)
Working with Images (11)
Working with videos (2)
WP Database (1)