Advertisement
salmancreation

Require a featured image before you can publish post

Jan 8th, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.62 KB | None | 0 0
  1. Require a featured image before you can publish post
  2.  
  3.  
  4. If you would like to require that all posts have a featured image before they can be published add this snippet to the functions.php of your wordpress theme. When you try and publish a post without a featured image you get an admin message “You must select Featured Image. Your Post is saved but it can not be published.” Great way to ensure all your posts have a featured image before they are publish.
  5.  
  6. add_action('save_post', 'wpds_check_thumbnail');
  7. add_action('admin_notices', 'wpds_thumbnail_error');
  8.  
  9. function wpds_check_thumbnail($post_id) {
  10.  
  11.     // change to any custom post type
  12.     if(get_post_type($post_id) != 'post')
  13.         return;
  14.    
  15.     if ( !has_post_thumbnail( $post_id ) ) {
  16.         // set a transient to show the users an admin message
  17.         set_transient( "has_post_thumbnail", "no" );
  18.         // unhook this function so it doesn't loop infinitely
  19.         remove_action('save_post', 'wpds_check_thumbnail');
  20.         // update the post set it to draft
  21.         wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
  22.  
  23.         add_action('save_post', 'wpds_check_thumbnail');
  24.     } else {
  25.         delete_transient( "has_post_thumbnail" );
  26.     }
  27. }
  28.  
  29. function wpds_thumbnail_error()
  30. {
  31.     // check if the transient is set, and display the error message
  32.     if ( get_transient( "has_post_thumbnail" ) == "no" ) {
  33.         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>";
  34.         delete_transient( "has_post_thumbnail" );
  35.     }
  36.  
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement