When the foreach
loop is from get_posts()
, you need to run setup_postdata()
for each post if you want to use themplate tags inside the loop like the_category()
, if not you can get unexpected behaviour. Also, you will need to run wp_reset_postdata()
after the foreach
loop. Note that the_category
and similar template tags actually displays/echoes the output, so, if you want to concatenate the output in a string you should use get_the_category()
instead.
function my_get_display_author_posts() {
global $authordata, $post;
$authors_posts = get_posts( array( 'author' => $authordata->ID,'posts_per_page' => 6, 'post__not_in' => array( $post->ID ) ) );
$output="<ul>";
foreach ( $authors_posts as $authors_post ) {
// Build a comma separated categories list
// You can customize as needed
// or use get_the_category_list() for quick and delimited list of categories
// http://codex.wordpress.org/Function_Reference/get_the_category_list
$categories = get_the_category($authors_post->ID);
$categories_string = '';
$separator=", ";
if($categories) {
foreach($categories as $category){
$categories_string .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
}
$categories_string = trim($categories_string, $separator);
}
$image = wp_get_attachment_image_src( get_post_thumbnail_id($authors_post->ID), 'related-author' );
$output .= '<li>
<a class="title" href="' . get_permalink($authors_post->ID) . '">
<strong>' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '</strong>
<img src="'.$image[0].'">
</a>
<span>'.get_the_time('m.d.y', $authors_post->ID ).'</span>'.$categories_string.'
</li>';
}
$output .= '</ul>';
return $output;
}