
本文介绍了如何在WordPress中获取与特定分类法(taxonomy)关联的用户ID列表。通过使用get_users()函数和WP_Query类,我们可以遍历所有用户,并检查他们是否发布了与特定分类法相关的文章。此外,还提供了一种使用$wpdb对象直接执行SQL查询的方法,以更高效地获取用户ID。
此方法通过遍历所有用户,并使用 WP_Query 检查每个用户是否发布了与特定分类法相关的文章。
$user_args = array( 'orderby' => 'ID' );
$users = get_users($user_args);
// 循环遍历每个用户
foreach($users as $user){
$user_posts = new WP_Query(array(
'post_type' => 'product', // 你的自定义文章类型
'author' => $user->ID,
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat', // 你的自定义分类法slug
'field' => 'term_id',
'terms' => 22 // 你的分类法term ID
)
)
));
if( $user_posts->have_posts() ) {
echo $user->first_name . ' ' . $user->last_name. ' associated with taxonomy 22'."</br>";
}
}代码解释:
注意事项:
限制特定用户ID:
如果你只想查询特定用户ID,可以使用 include 参数:
$user_args = array(
'include' => array(11, 33, 52, 57, 997) // 添加你的用户ID,用逗号分隔
);
$users = get_users( $user_args );
//Loop through each peche author
foreach($users as $user){
$user_posts = new WP_Query(array(
'post_type' => 'product', // 你的自定义文章类型
'author' => $user->ID,
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat', // 你的自定义分类法slug
'field' => 'term_id',
'terms' => 22 // 你的分类法term ID
)
)
));
if( $user_posts->have_posts() ) {
echo $user->ID."</br>";
}
}此方法直接执行 SQL 查询,效率更高,尤其是在用户数量很多的情况下。
global $wpdb;
$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 );
}代码解释:
注意事项:
示例,使用 $wpdb->prepare():
global $wpdb;
$term_taxonomy_id = 1186; // 你的 term_taxonomy_id
$all_ids = array();
$query = $wpdb->prepare("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 = %d", $term_taxonomy_id);
$result = $wpdb->get_results( $query, ARRAY_A );
foreach ( $result as $key => $id ) {
$all_ids[] = $id['ID'];
}
if( !empty( $all_ids ) ){
echo implode( ',', $all_ids );
}本文介绍了两种在 WordPress 中获取与特定分类法关联的用户ID的方法。第一种方法使用 get_users() 和 WP_Query,代码更易于理解,但效率较低。第二种方法使用 $wpdb 直接执行 SQL 查询,效率更高,但需要一定的 SQL 知识。选择哪种方法取决于你的具体需求和技术水平。推荐使用 $wpdb->prepare() 来构建SQL查询,以避免潜在的安全风险。
以上就是获取与特定分类法关联的用户ID列表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号