In WP, I would like to get the list of user IDs that are associated with taxnomy. I know the SQL query but I am not sure how to build a line of php code to get the same result (something like $users = get_user_by(parameters)) ?
SELECT u.ID
FROM wp_users u
INNER JOIN wp_term_relationships r
ON u.ID = r.object_id
WHERE u.user_status = 0
AND r.term_taxonomy_id = 1186
turning this into something like this
$users = get_user_by(parameters) or
get_objects_in_term(parameters)
I have checked a few posts online but very few post about user-taxonomy relation... so please help me....
Thank you so much!!
CodePudding user response:
First, you have to get all users using the get_users()
function. then iterate the loop of users and based on that get user posts using author
and tax_query
. try below code.
$user_args = array( 'orderby' => 'ID' );
$users = get_users($user_args);
//Loop through each peche author
foreach($users as $user){
$user_posts = new WP_Query(array(
'post_type' => 'product', // your custom post type
'author' => $user->ID,
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat', // your custom taxonomy slug
'field' => 'term_id',
'terms' => 22 // your term id.
)
)
));
if( $user_posts->have_posts() ) {
echo $user->first_name . ' ' . $user->last_name. ' associated with taxonomy 22'."</br>";
}
}
UPDATE as per OP requested
$user_args = array(
'include' => array(11, 33, 52, 57, 997) // add your user ids here by comma seprate.
);
$users = get_users( $user_args );
//Loop through each peche author
foreach($users as $user){
$user_posts = new WP_Query(array(
'post_type' => 'product', // your custom post type
'author' => $user->ID,
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat', // your custom taxonomy slug
'field' => 'term_id',
'terms' => 22 // your term id.
)
)
));
if( $user_posts->have_posts() ) {
echo $user->ID."</br>";
}
}
UPDATE as per OP requested in comments.
$all_ids = array();
$result = $wpdb->get_results( "SELECT u.ID FROM wp_users u INNER JOIN wp_term_relationships r ON u.ID = r.object_id WHERE u.user_status = 0 AND r.term_taxonomy_id = 1186", ARRAY_A );
foreach ( $result as $key => $id ) {
$all_ids[] = $id['ID'];
}
if( !empty( $all_ids ) ){
echo implode( ',', $all_ids );
}