当foreach
循环来自get_posts()
, 你需要跑步setup_postdata()
对于每个帖子,如果你想在循环中使用模板标签the_category()
, 如果没有,你可能会有意想不到的行为。此外,您还需要运行wp_reset_postdata()
在foreach
环请注意the_category
而类似的模板标记实际上会显示/回显输出,因此,如果要将输出串联成字符串,应该使用get_the_category()
相反
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;
}