获取与分类关联的用户列表

Get a list of users that are associated with taxonomy

在 WP 中,我想获取与分类相关的用户 ID 列表。 我知道 SQL 查询,但我不确定如何构建一行 php 代码来获得相同的结果(类似于 $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

把它变成这样的东西

$users  = get_user_by(parameters) or 
get_objects_in_term(parameters)

我在网上查了一些 post 但关于用户-分类关系的 post 很少...所以请帮助我....

非常感谢!!

首先,您必须让所有用户使用 get_users() 函数。然后迭代用户循环并基于此使用 authortax_query 获取用户帖子。试试下面的代码。

$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>";

    } 
}

根据 OP 要求更新

$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>";

    } 
}

更新 根据评论中要求的 OP。

$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 );
}