如何从多个角色查询发布?

时间:2011-07-16 作者:Andrew

我使用下面的代码从另一个答案中查询来自1个自定义角色的帖子,例如“朋友”。我想我可以用逗号分隔角色,将帖子从多个角色中列出,但这不起作用。我还有别的办法写吗?我试过了\'role\' => \'friends\', \'enemies\'\'role\' => \'friends, enemies\' 但我想get_users 仅支持一个角色。

<?php
$friends = get_users( array( \'role\' => \'friends\' ) );
$friend_ids = array();

foreach( $friends as $friend ) 
$friend_ids[] = $friend->ID;

$news = new WP_Query( array( \'author\' => implode( \',\', $friend_ids ), \'post_type\' => \'news\', \'paged\' => get_query_var(\'paged\') ) ); ?>

2 个回复
最合适的回答,由SO网友:Scott 整理而成

只需执行两次get\\u users()并合并结果:

<?php
$friends = get_users( array( \'role\' => \'friends\' ) );
$enemies = get_users( array( \'role\' => \'enemies\' ) );

$friends_n_foe = array_merge($friends, $enemies);

$IDs = array();

foreach( $friends_n_foe as $person ) {
    $IDs[] = $person->ID;
}

$news = new WP_Query( array( \'author\' => implode( \',\', $IDs ), \'post_type\' => \'news\', \'paged\' => get_query_var(\'paged\') ) );
?>

SO网友:Rajeev Vyas

下面是从中获取角色的用户ID的函数http://sltaylor.co.uk/blog/get-wordpress-users-by-role/

function getUsersByRole( $roles ) {  
    global $wpdb;  
    if ( ! is_array( $roles ) ) {  
        $roles = explode( ",", $roles );  
        array_walk( $roles, \'trim\' );  
    }  
    $sql = \' 
        SELECT  ID, display_name 
        FROM        \' . $wpdb->users . \' INNER JOIN \' . $wpdb->usermeta . \' 
        ON      \' . $wpdb->users . \'.ID              =       \' . $wpdb->usermeta . \'.user_id 
        WHERE   \' . $wpdb->usermeta . \'.meta_key     =       \\\'\' . $wpdb->prefix . \'capabilities\\\' 
        AND     ( 
    \';  
    $i = 1;  
    foreach ( $roles as $role ) {  
        $sql .= \' \' . $wpdb->usermeta . \'.meta_value LIKE    \\\'%"\' . $role . \'"%\\\' \';  
        if ( $i < count( $roles ) ) $sql .= \' OR \';  
        $i++;  
    }  
    $sql .= \' ) \';  
    $sql .= \' ORDER BY display_name \';  
    $userIDs = $wpdb->get_col( $sql );  
    return $userIDs;  
}  
我应该工作。。。可能是您有语法错误。。。

请参见下页中的。。显示多个作者的帖子http://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters

结束

相关推荐