logo

$10
How do I query posts based on the user's role (security level)

I need to create a bunch of unique user roles, such as:

stocking
checking
customer-service
complaints.

No worries here. I think the Capabilities Manager plugin will let me create the roles I need.

But I also need to query based on these roles. In other words, "Get all posts created by users who have the role 'complaints'".

How do I perform such queries? How do I get posts based on user role?

paddy | 12/24/09 at 2:18pm | Edit


(2) Possible Answers Submitted...

  • avatar
    Last edited:
    12/26/09
    10:01pm
    scribu says:

    Here's some code you can use (not tested):


    // Add SQL WHERE clause
    function limit_author_role($where) {
    global $wpdb, $restrict_to_role;

    $where .= $wpdb->prepare(" AND $wpdb->posts.post_author IN (
    SELECT user_id FROM $wpdb->usermeta
    WHERE $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities'
    AND $wpdb->usermeta.meta_value LIKE %s
    )", '%' . $restrict_to_role . '%');

    return $where;
    }

    // Wrapper function
    function query_posts_by_author_role($query, $role) {
    global $restrict_to_role;

    $restrict_to_role = $role;

    add_filter('posts_where', 'limit_author_role');
    query_posts($query);
    remove_filter('posts_where', 'limit_author_role');
    }


    You use it just like you use query_posts(), except you add the author role as the second parameter:

    query_posts_by_author_role('cat=1,2,3&showposts=20', 'editor');


    Previous versions of this answer: 12/24/09 at 6:36pm | 12/24/09 at 6:41pm

  • avatar
    Last edited:
    12/26/09
    10:01pm
    Max says:

    If you use that plugin you could access the function ak_get_user_role($user_id)
    It returns the user role from an user id.

    This code get the IDs of your users, builds a query string with the IDs of the user belonging to a determinated role (administrator in the example) and call query_posts.

    After that you could run a Loop and print what you want



    $users_ids = $wpdb->get_results("SELECT id FROM wp_users");

    $my_users = array();

    for($i = 0; $i<sizeof($users_ids); $i++)
    {
    if(ak_get_user_role($users_ids[$i]) == 'administrator')
    {
    $my_users[] = $users_ids[$i];
    }
    }

    query_posts('author=' . implode(',', $my_users));

    [your loop here]



    Happy holidays :)

    Previous versions of this answer: 12/24/09 at 8:02pm

This question has expired.





Current status of this question: Completed