Query users by custom taxonomy and user role

I’m trying to make a query for users using WP_User_Query()
I need to filter users by role shop_manager and custom taxonomy called shop-category and current taxonomy term ID.

The code I have so far:

<?php 

// WP_User_Query arguments
$args = array (
    'role'           => 'shop_manager',
    'order'          => 'DESC',
    'orderby'        => 'user_registered',
    'tax_query' => array(
    array('taxonomy' => 
    'shop-category', 
    'field' => 'id', 
    'terms' => $term_id ) ) 
);

// The User Query
$user_query = new WP_User_Query( $args );

// The User Loop
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
        echo '<li><span>' . esc_html( $user->shop_name ) . '</span></li>';
    }
} else {
    // no users found
}

?>

To get term ID I was using this code

<?php $queried_object = get_queried_object();
$term_id = $queried_object->term_id; 

echo 'ID = '. $term_id;?>

Now it’s showing all users with shop_manager role. Looks like taxonomy doesn’t work.

2 s
2

Apparently there is no core implementation of 'tax_query' in WP_User_Query yet.

Check the ticket here for more info –> https://core.trac.wordpress.org/ticket/31383

Nevertheless there is an alternative way using get_objects_in_term

$taxonomy = 'shop-category';
$users = get_objects_in_term( $term_id, $taxonomy );    

if(!empty($users)){

    // WP_User_Query arguments
    $args = array (
        'role'           => 'shop_manager',
        'order'          => 'DESC',
        'orderby'        => 'user_registered',
        'include'        => $users
    );

    // The User Query
    $user_query = new WP_User_Query( $args );

    // The User Loop
    if ( ! empty( $user_query->results ) ) {
        foreach ( $user_query->results as $user ) {
            echo '<li><span>' . esc_html( $user->shop_name ) . '</span></li>';
        }
    } 
    else {
        // no shop_manager found 
    }
}
else {
    // no users found
}

Leave a Comment