Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

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


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


No worries here. I think the [[LINK href=""]]Capabilities Manager plugin[[/LINK]] 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?

Answers (2)


scribu answers:

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');
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');


Max answers:

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 [[LINK href=""]]query_posts[[/LINK]].

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 :)