How can a PHP function be used to prevent users from commenting on a thread in a forum?

To prevent users from commenting on a thread in a forum, you can create a PHP function that checks if a user is authorized to comment based on certain criteria such as their user role or permissions. If the user is not authorized, the function can prevent the comment from being posted.

function can_user_comment() {
    // Check if user is logged in
    if(!is_user_logged_in()) {
        return false;
    }
    
    // Check user role or permissions
    if(current_user_can('moderate_comments')) {
        return true;
    } else {
        return false;
    }
}

// Implementation example
if(!can_user_comment()) {
    echo "You are not authorized to comment on this thread.";
} else {
    // Allow user to post comment
}