Code Snippets

Require Featured Image In WordPress

Maan
Mar 16, 2014
2 min read
251 words

Many WordPress blog users forget to add featured image in their blog post while publishing their posts. If they remain forgetting to add the featured images, it would be time-consuming to re-edit those blog posts for assigning featured images.

This  Snippet will help you to have all those posts that required featured image before they publish. You just need to add this snippet to the functions.php of your WordPress theme. When you try to publish a post without a featured image you get an admin message ”You must select Featured Image. Your Post is saved but it cannot be published.’

[php]
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;Change Text Selection Color With CSS

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 “

You must select Post Thumbnail. Your Post is saved but it can not be published.Ridiculously Responsive Social Sharing Buttons

“;
delete_transient( “has_post_thumbnail” );
}

}
[/php]

Maan

Author

Maan is a Lead Frontend Engineer and Creative Director with 10+ years of industry experience blending UI/UX design with React-based development. A multifaceted practitioner, he has spent a decade turning abstract inspiration into deployed, scalable reality. Maan’s expertise lies in high-fidelity prototyping and component architecture, which he shares through insightful technical writing with the next generation of developers. His unique approach ensures that pixels not only meet passion but also rigorous performance standards.

View all posts

Continue reading

You might also like

Leave a Reply

Your email address will not be published. Required fields are marked *

Menu