To add users to Public Group using Apex, we have to insert the entries in GroupMember entity.
As per the following trigger, when a user record is created, the created user is assigned to the hard coded public group id.
Sample Trigger:
trigger AddToPG on User (after insert) {
List<GroupMember> GMlist = new List<GroupMember>();
for(User U : Trigger.New) {
if(U.isActive) {
GroupMember GM = new GroupMember();
GM.GroupId = '00GU0000001Zjeq';
GM.UserOrGroupId = U.Id;
GMList.add(GM);
}
}
if(!GMList.isEmpty()) {
System.debug('Group Member List is ' + GMList);
insert GMList;
}
}