
Earlier today Miriam at WordPress Garage posted a quick challenge: how to display a list of authors who had posted in a particular category. I had an idea at the time but I wasn’t in a position to test the idea, so now I am home I have written a quick function to do just that.
These two functions are best placed in your functions.php file or can be added loose to the category template file, either would be fine.
[php]
function get_authors_by_cat($cat_id, $sort = true){
$author_id_array = array();
$author_details_array = array();
$cat_posts = get_posts('category='.(int) $cat_id);
foreach ($cat_posts as $cat_post){
if (!in_array($cat_post->post_author , $author_id_array)){
$author_id_array[] = $cat_post->post_author;
$author_details_array[] = get_userdata($cat_post->post_author);
}
}
if ($sort === true ){
usort($author_details_array , 'author_by_cat_sort');
}
return $author_details_array;
}
function author_by_cat_sort($a, $b){
$al = strtolower($a->display_name);
$bl = strtolower($b->display_name);
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
There are two functions here, the first retrieves all the posts from the category and loops through them to make sure. The second function is a callback for the usort function. This allows the list to be sorted by the display name of the authors.
This could be done more efficiently by querying the database directly but I wanted to avoid that option as a lot of people are not comfortable doing that themselves.
To use the function in your theme you need to include the following in your where you want the list to appear (replacing the number 18 with the ID of the category that you want to list authors for.
$authordata_array = get_authors_by_cat(18, $sort = true);
} ?>[php]
foreach ($authordata_array as $authordata){
?>
Notice that in the foreach loop you should be able to use the normal author based template tags. You can find a list at http://codex.wordpress.org/Template_Tags
(__)
`
Rebecca,
I had it working on WordPress 2.5 and 2.3. What errors did you get?
DId you copy and paste directly or did you change the fancy quotes to normal ones? i.e. the single quotes around the sections in red above?
(__)
`
Thanks for posting this code – I tried it out but got error warnings. I tried putting it in the functions.php and then tried putting it in the category template page with no luck. Did you have success in getting your code to work?