Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auto-assign custom Group to new WooCommerce customers
// When working with both WooCommerce and Groups plugins, I needed a way to auto-assign
// users with the Customer role to a specific group, separate from the default Registered group.
$AUTO_ASSIGNED_GROUP_NAME = 'General';
function my__edit_user_created_user( $user_id ) {
$user = get_userdata( $user_id );
$roles = empty( $user->roles ) ? array() : $user->roles;
if ( in_array( 'customer', $roles ) ) {
$existing = my__get_users_groups( $user_id );
if ( empty( $existing ) || count( $existing ) < 2 ) { // ignore if only Registered
$default_group = Groups_Group::read_by_name( $AUTO_ASSIGNED_GROUP_NAME );
if ( $default_group ) {
$default_group_id = $default_group->group_id;
}
if ( $default_group_id ) {
Groups_User_Group::create(
array(
'user_id' => $user_id,
'group_id' => $default_group_id
)
);
}
}
}
}
function my__get_users_groups( $user_id ) {
global $wpdb;
$result = false;
$user_group_table = _groups_get_tablename( 'user_group' );
$user_groups = $wpdb->get_row( $wpdb->prepare(
"SELECT * FROM $user_group_table WHERE user_id = %d",
Groups_Utility::id( $user_id )
) );
if ( $user_groups !== null ) {
$result = $user_groups;
}
return $result;
}
add_action( 'edit_user_created_user', 'my__edit_user_created_user', 100, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment