WordPress Snippets at WPcustoms

Require a featured image for posts

The following code can be used to make the post thumbnail a requirement. When you save the post and it doesn’t have a featured image then you will see the post is set back to a draft and an error message is displayed on the screen.


/**
 * Snippet Name: Require a featured image for posts
 * Snippet URL: https://wpcustoms.net/snippets/require-a-featured-image-for-posts/
 */
  function wpc_validate_thumbnail($post_id)
{
    // Only validate post type of post - feel free to use your custom post type
    if(get_post_type($post_id) != 'post')
        return;

  // Check post has a thumbnail
    if ( !has_post_thumbnail( $post_id ) ) {
      // Confirm validate thumbnail has failed
        set_transient( "wpc_validate_thumbnail_failed", "true" );

        // Remove this action so we can resave the post as a draft and then reattach the post
        remove_action('save_post', 'wpc_validate_thumbnail');
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
  add_action('save_post', 'wpc_validate_thumbnail');
    } else {
      // If the post has a thumbnail delete the transient
        delete_transient( "wpc_validate_thumbnail_failed" );
    }
}
add_action('save_post', 'wpc_validate_thumbnail');



function wpc_validate_thumbnail_error()
{
    // check if the transient is set, and display the error message
    if ( get_transient( "wpc_validate_thumbnail_failed" ) == "true" ) {
        echo "

A post thumbnail must be set before saving the post.

"; delete_transient( "wpc_validate_thumbnail_failed" ); } } add_action('admin_notices', 'wpc_validate_thumbnail_error');