How to query post by user role?

I want to query posts by their author role. And do something with the post based on the role.

I know we can get the post by get_posts or WP_query, the problem is there are no argument to sort the post based on the author role. Or, we also can combine get_users and get_posts together, like this

$users = get_users(array(role => 'author'));
foreach($users as $user){
//here we can use get_posts to query the posts by the $user->ID   
} .....

this is too clumsy to doing this. I want to know if there any other way to query the posts based on the role, SQL query perhaps?

4 s
4

I haven’t really messed around with custom post queries before, but here is my try at a solution:

function get_posts_by_author_role($role) {
    global $wpdb;
    return $wpdb->get_results( "SELECT p.* FROM {$wpdb->posts} p, {$wpdb->usermeta} u"
                                ." WHERE    p.post_type="post""
                                ." AND      p.post_status="publish""
                                ." AND      u.user_id       = p.`post_author`"
                                ." AND      u.meta_key      = 'wp_capabilities'"
                                ." AND      u.meta_value    LIKE '%\"{$role}\"%'" );
}

This function will return posts only if their author has the role specified.
It is tested and working on my local install of 3.4, but let me know if you are having any problems with it.

I hope this helps.

Example Usage:

$posts = get_posts_by_author_role('author');
foreach($posts as $post) echo $post->post_title, '<br />';

Leave a Comment