Get a User’s Custom Taxonomies


Home  >  Blog  >  Posted on September 12, 2012

Code WordPress

Justin Tadlock has an article here on setting up custom user taxonomies in WordPress. Something he didn’t include was how to get a single user’s taxonomy values. I had to dig around core a little bit for it but this will do it.

/**
 * Return a single user's custom taxonomy values
 *
 * @param int $user_id The user's ID who we want to query
 * @param string $term_slug The slug of the term we want to query for that user
 */

function prefix_get_user_terms( $user_id, $term_slug ) {
     return wp_get_object_terms( $user_id, $term_slug );
}

And if you want to check if a user has a specific value of a certain taxonomy:


/**
 * Make sure that a given user has a taxonomy value. 
 *
 * @param int $user_id The user's ID who we want to query
 * @param string $term_slug The slug of the term we want to query for that user
 * @param string $term_value_slug The slug for the value of the term that we want to check against
 */
function prefix_user_has_term($user_id,$term_slug,$term_value_slug)   {
        return is_object_in_term($user_id,$term_slug,$term_value_slug);
}

And if you want to query all users that have a certain term:

function get_users_with_term($term_taxonomy_id,$terms)   {

	global $wpdb;
	
	$users = $wpdb->get_results($wpdb->prepare( 
			"			
			SELECT * FROM $wpdb->users as usr
			INNER JOIN $wpdb->term_relationships AS term_r
				ON term_r.object_id = usr.ID
			WHERE term_r.term_taxonomy_id IN (%s)
			",
			$term_taxonomy_id
	),ARRAY_A);
	
	if($users)  {
		return $users;
	} else {
		return false;
	}
}

Both of these functions could be improved a lot by not taking such strict variables, but they get the job done for what I’m doing.

  • Justin Tadlock

    Those could definitely be useful functions if you need wrappers for the core WP functions.

    For your first wrapper function, you don’t need to pass the user object. You can pass the user ID directly into wp_get_object_terms(). So, you could literally break that down to three lines of code.

    For your second function, take a look at the WordPress is_object_in_term() function. Your function should just be a wrapper for that.

    Also, just for clarification in your code, your functions should be named get_user_terms() and user_has_term() (you’ll probably want to prefix those too).

    Hope that helps!

    • nickbudden

      Thanks Justin, looks like I wasn’t able to find those functions when looking before but have switched the code to show them.