Created
February 10, 2015 23:43
-
-
Save paulvanbuuren/cdcc7c35c9851d3b6483 to your computer and use it in GitHub Desktop.
WordPress: Require Featured Image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from: http://www.codeinwp.com/blog/wordpress-image-code-snippets/ | |
// ============================================================================ | |
// WordPress: Require Featured Image | |
// | |
// If you add the following code to your functions.php and try to publish a post that doesn’t have a featured image, | |
// you will receive the following message: “You must select a Featured Image before your Post can be published.” | |
// ============================================================================ | |
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" ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This does not seem to work with Gutenberg