Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created September 9, 2011 02:59
Show Gist options
  • Save mjangda/1205393 to your computer and use it in GitHub Desktop.
Save mjangda/1205393 to your computer and use it in GitHub Desktop.
Using a taxonomy to store user-to-usergroup relationships
<?php
// Assuming we already have registered the taxonomy.
$usergroup_taxonomy = 'ef_usergroups';
// Tell WordPress that we can make associations between users and the usergroups taxonomy.
register_taxonomy_for_object_type( $usergroup_taxonomy, 'user' );
// Sample code
$user = WP_User( 1 );
wp_set_object_terms( $user->ID, 'science-writers', $usergroup_taxonomy ); // add user to science-writers usergroup
wp_set_object_terms( $user->ID, 'photographers', $usergroup_taxonomy ); // add user to photographers usergroup
$user_usergroups = wp_get_object_terms( $user->ID, $usergroup_taxonomy ); // get list of usergroups that user belongs to
$usergroup_id = get_term_by( 'slug', 'photographers' );
$users_in_usergroup = get_objects_in_term( $usergroup_id , $usergroup_taxonomy ); // Get user ids of users in usergroup
foreach( (array) $users_in_usergroup as $user_id ) {
$user = get_user_by( 'id', $user_id );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment