How to Hide and Disable Comments for Non-Logged-In Users on WordPress

The code snippet below will restrict access to the comments section on your WordPress site for non-logged-in users. It prevents non-logged-in users from viewing existing comments and also from leaving new comments.

// Custom function to hide comments for non-logged-in users
function ts_hide_comments_for_non_logged_in($comments, $post_id) {
    if (!is_user_logged_in()) {
        return []; // Return an empty array for non-logged-in users
    }
    return $comments; // Show comments for logged-in users
}
add_filter('comments_array', 'ts_hide_comments_for_non_logged_in', 10, 2);

// Custom function to close comments for non-logged-in users
function ts_close_comments_for_non_logged_in($open, $post_id) {
    if (!is_user_logged_in()) {
        return false; // Disable comments for non-logged-in users
    }
    return $open; // Keep comments open for logged-in users
}
add_filter('comments_open', 'ts_close_comments_for_non_logged_in', 20, 2);