Sunday 2 February 2014

Featured Image Required Before Publishing A Post

When blogger wants featured image for each and every post in a blog then this simple tutorial is needed.
Every time when we post a content by forgetting a featured image and again we edit and add featured image to the post , it is regular process many bloggers face. In order to reduce this kind of headaches then follow this tutorial.

When you add content and forget about adding featured image, then admin will display error "You must select Featured Image. Your Post is saved but it can not be published."
Add this snippet in your functions.php file.



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 "
You must select Featured Image. Your Post is saved but it can not be published.
"; delete_transient( "has_post_thumbnail" ); } }

No comments:

Post a Comment