Lego2012
12/13/2016 - 9:57 AM

Posts and Pages - Require a featured image before you can publish posts

Posts and Pages - Require a featured image before you can publish posts

<?php
// Do NOT include the opening php tag

<!--
Publishing a blog post or a page on WordPress is easy but in many cases words alone aren't enough: news, product pages, etc. they all need images to stand out and communicate better. So how about making it mandatory for your users to add a featured image to their post or page unless they aren't able to publish it? Great, open functions.php and apply the following code: 
-->

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 add a Featured Image before publishing this. Don't panic, your post is saved.</strong></p></div>";
    delete_transient( "has_post_thumbnail" );
  }
}

<!-- 
Isn't this useful? Of course, you can set your custom alert message by editing whatever fits your needs. 
-->