Menu bar

Wednesday 14 January 2015

Publish the post if and only if the featured image is set.

SET FEATURED IMAGE AND PUBLISH IT


Dont allow the user to publish the post until the featured image is set.

sometimes after publsihing the post user come to know that featured image is not set. and he/she will try to add featured image once publsihed.<br />
How it look if the post was unable to publish until the featured image is set?

yes, you can do this with wordpress hook.
you have to use "save_post" hook to check whether the post has thumbnail i.e. the featured image is set or not and you have to use "admin_notices" hook to display message above post title.

place this snippet in your functions.php file

add_action('save_post', 'check_thumbnail');
add_action('admin_notices', 'thumbnail_error');

function check_thumbnail($post_id) {
    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 and it will not publish until featured image is set.
        remove_action('save_post', 'check_thumbnail');
        // update the post and set it to draft
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
        add_action('save_post', 'check_thumbnail');
    } else {
        delete_transient( "has_post_thumbnail" );
    }
}

function thumbnail_error()
{
    if ( get_transient( "has_post_thumbnail" ) == "no" ) {
        echo "<div id='message' class='error'><p><b style="color:#F00;">Select Featured Image and Publish it.</b></p></div>";
        delete_transient( "has_post_thumbnail" );
    }

}

No comments: