按自定义分类和用户角色查询用户

时间:2015-08-13 作者:Erik

我正在尝试为使用WP_User_Query()我需要按角色筛选用户shop_manager 和自定义分类法shop-category 和当前分类术语ID。

到目前为止我掌握的代码:

<?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
}

?>
为了获取术语ID,我使用了以下代码

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

echo \'ID = \'. $term_id;?>
现在,它向所有用户显示shop_manager 角色分类法似乎不起作用。

2 个回复
SO网友:RafaSashi

显然,没有\'tax_query\' 在里面WP_User_Query 然而

查看此处的票证以了解更多信息-->https://core.trac.wordpress.org/ticket/31383

尽管如此,还有一种替代方法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
}

SO网友:webtoure

没有tax_query 的参数WP_User_Query 班因为你已经用user-meta 我只能假设你ID (甚至是术语名称本身?)特定的shop-category 术语作为用户元条目。

在这种情况下,您需要这样的东西:

// The \'WP_User_Query\' arguments array
$args = array(
    \'role\'          => \'shop_manager\',
    \'order\'         => \'DESC\',
    \'orderby\'       => \'user_registered\',
    \'meta_key\'      => \'shop_name\', // Is this the meta key you are using?
    \'meta_value\'    => \'the_term_name_or_term_id\', // Based on however you store your meta data
    \'meta_compare\'  => \'=\',
);

结束

相关推荐

Get_Terms()返回空数组

我已经阅读了所有关于显示自定义分类法术语的帖子,但它仍然不起作用。好的,下面是代码:<?php //part of template-offer.php $taxonomy = \'brand\'; $term_args=array( \'hide_empty\' => false, \'orderby\' => \'name\', \'order\' => \'ASC\' ); $tax_terms =