Opened 10 years ago
Closed 10 years ago
#37256 closed feature request (duplicate)
Support for User taxonomies: Automatically add menu items and admin screens, add support for tax args to WP_User_Query
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Priority: | normal | |
| Severity: | normal | Version: | 4.5.3 |
| Component: | Users | Keywords: | |
| Focuses: | Cc: |
Description
Apparently it is possible to register a taxonomy for Users:
function create_user_tax() {
register_taxonomy(
'group',
'user',
array(
'label' => __( 'Group' )
)
);
}
add_action('init', 'create_user_tax');
as described in [Justin Tadlock's tutorial](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress).
And wp_set_object_terms() and wp_get_object_terms() already work (though it *just* occurred to me there could be a slight issue if a user ID has the same ID as a post and they share a taxonomy), but as the tutorial describes you need to add your own Manage terms page *and* your own term count callback. I'd like to propose that those be added automatically just like any post type taxonomy.
I'd also like to propose WP_User_Query support tax_query args the same as posts. The query can already be modified via pre_get_users to support this, I think it'd just be cooler if it were in core.
function user_tax_query( $query ) {
global $wpdb;
// fake a tax query
if ( isset( $query->query_vars['tax_query'] ) && is_array( $query->query_vars['tax_query'] ) ) {
$tax_args = $query->query_vars['tax_query'];
if ( isset( $tax_args['taxonomy'] && isset( $tax_args['terms'] ) ) ) {
$args = array(
array(
'taxonomy' => $tax_args['taxonomy'],
'field' => 'slug', // eventually account for IDs
'terms' => isset( $tax_args['terms'] ),
),
);
$sql = get_tax_sql( $args, $wpdb->prefix . 'users', 'ID' );
if( isset( $sql['join'] ) ){
$query->query_from .= $sql['join'];
}
if( isset( $sql['where'] ) ){
$query->query_where .= $sql['where'];
}
}
}
}
add_action( 'pre_user_query', 'user_tax_query' );
With that filter in place a WP_User_Query can query the users in a specific taxonomy:
$args = array( 'tax_query' => array(
array(
'taxonomy' => 'group',
'field' => 'slug',
'terms' => 'blue-group',
),
)
);
$users = new WP_User_Query( $args );
Hi @helgatheviking ! Thanks for the ticket. The specific idea of supporting 'tax_query' in
WP_User_Queryis being discussed in #31383, in the more general context of better core support for user taxonomies. Please follow along there!