Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghwoodard/068498802c3fbd9ef9d0ef714ca8ba21 to your computer and use it in GitHub Desktop.
Save ghwoodard/068498802c3fbd9ef9d0ef714ca8ba21 to your computer and use it in GitHub Desktop.
Require a Featured Image Before You Can Publish a Post
<?php
/*
A great function that will display a message to the user that a Featured Image is missing and is required in order to publish
a new post.
*/
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 "&lt;div id='message' class='error'&gt;&lt;p&gt;&lt;strong&gt;You must add a Featured Image. Your Post is saved as a draft but it can not be published.&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt;";
delete_transient( "has_post_thumbnail" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment