Prevent publishing the post before setting a featured image?

The has_post_thumbnail() works for me, in WP versions 3.4.1 and other most recently.
But in this logic, because the WP will publish the post even with exit or wp_die() or anything to terminate the PHP script. For prevent that the post stay with published status, you will need to update the post before terminate. Look the code below:

add_action('save_post', 'prevent_post_publishing', -1);
function prevent_post_publishing($post_id)
{
    $post = get_post($post_id);

    // You also add a post type verification here,
    // like $post->post_type == 'your_custom_post_type'
    if($post->post_status == 'publish' && !has_post_thumbnail($post_id)) {
        $post->post_status="draft";
        wp_update_post($post);

        $message="<p>Please, add a thumbnail!</p>"
                 . '<p><a href="' . admin_url('post.php?post=" . $post_id . "&action=edit') . '">Go back and edit the post</a></p>';
        wp_die($message, 'Error - Missing thumbnail!');
    }               
}

Leave a Comment