Require Users to Set a Featured Image Before Publishing a Post in WordPress

Rich media is an important part of website readability. On a multi-author site, some editors try to save time, or simply forget, and publish posts without setting a featured image. That hurts the user experience to some extent. If we check whether the user has set a featured image before the post is published, and block publishing when it is missing, the problem becomes easy to avoid. In WordPress, this can be implemented very easily.

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');

function wpds_check_thumbnail($post_id) {

    // 判断是否为文章
    if(get_post_type($post_id) != 'post')
        return;
    
    if ( !has_post_thumbnail( $post_id ) ) {
        // 设置用户是否设置了图片的临时记录
        set_transient( "has_post_thumbnail", "no" );
        // 避免循环运行
        remove_action('save_post', 'wpds_check_thumbnail');
        // 保存文章并设置为草稿
        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()
{
    // 检查是否设置了特色图像,如果没有设置,显示提示信息
    if ( get_transient( "has_post_thumbnail" ) == "no" ) {
        echo "<div id='message' class='error'><p><strong>抱歉!发表文章之前,必须先设置一个特色图像!</strong></p></div>";
        delete_transient( "has_post_thumbnail" );
    }

}

Paste the code above into the theme’s functions.php file. The next time an editor tries to publish without a featured image, WordPress will stop the post from being published and show a reminder. Over time, that naturally helps editors build the habit of setting a featured image before publishing.

Related Posts

Leave a Reply

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