As I’ve mentioned couple of times before, WordPress is pretty amazing in adding hooks and hacks without modifying core components. User’s have so many options to customize it completely.
Sometime back we have written an article on adding Social media without any Javascript and it became very popular. Similar to that with the help of WordPress Featured Image
option you could beautify your blog layout and enhance the presentation of your blog. Theme developer can use the same featured image in number of different ways based on the type of theme.
Providing and adding Featured Image into WordPress post/page is not a mandatory option. Sometimes it may create blank spot on theme and may disturb your blog layout. In this tutorial we will go over tips on how to How to Force User to Upload Featured Image before Publishing a post?
Let’s get started:
- use these
save_post
andadmin_notices
actions - use
post_updated_messages
filters - use
has_post_thumbnail($post_id)
– which returns a boolean if a post has a Featured Image - During publish check if thumbnail is set?
- if not, go ahead and set transient variable to “no”
- If transient variable to “no” – set the admin notice with clear message
- if transient variable not “no” – publish a post
Insert below code to your theme’s functions.php
file
// save_post is an action triggered whenever a post or page is created or updated add_action('save_post', 'crunchify_verify_thumbnail'); add_action('admin_notices', 'crunchify_show_thumbnail_error'); function crunchify_verify_thumbnail($post_id) { // This applies to only type `post`. You could have this for `page` too 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( "crunchify_check_thumbnail", "no" ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'crunchify_verify_thumbnail'); // update the post set it to draft wp_update_post(array('ID' => $post_id, 'post_status' => 'draft')); add_action('save_post', 'crunchify_verify_thumbnail'); } else { delete_transient( "crunchify_check_thumbnail" ); } } function crunchify_show_thumbnail_error() { // Only show error message incase transient variable is set if ( get_transient( "crunchify_check_thumbnail" ) == "no" ) { echo "<div id='message' class='error'><p><strong>Howdy. You wont be able to `Publish` this post until you select a `Featured Image`.</strong></p></div>"; delete_transient( "crunchify_check_thumbnail" ); } }
Now if you try to publish a post without thumbnail image – you should see error message like this.
But with above code you may still get Post published
message. With below code you should be able to remove that message easily.
// Simple way to Remove published post notice while error handled add_filter( 'post_updated_messages', 'crunchify_disable_publish_successful_msg' ); function crunchify_disable_publish_successful_msg( $messages ) { return array(); }