How to query post by user role?

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