<?php
$author_query = array(
'posts_per_page' => 5,
'author' => $author->ID,
);
$author_posts = new WP_Query($author_query);
while($author_posts->have_posts()) : $author_posts->the_post(); ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> <br>
<?php endwhile;
?>
上面的代码将仅显示当前作者的帖子,
基本上是这样的,设置是我要显示5个帖子,而当前Author只有2个帖子,因此输出为:
1. Author Post
2. Author Post
但是我仍然想显示“管理员和编辑者”的帖子,但是我想优先显示“作者”的帖子。
所以基本上它应该变成这样;
1. Author Post
2. Author Post
3. Admin Post
4. Editor Post
5. Admin Post
如您所见,在显示admin和editor的其他帖子之前,优先显示作者的帖子。那就是我想要实现的。
答案 0 :(得分:1)
尝试下面的修改代码
<?php
// Get author posts
$author_query = array(
'posts_per_page' => 5,
'author' => $author->ID,
);
$authorpostswpquery = new WP_Query($author_query);
$authorposts = $authorpostswpquery->posts;
//Get admin role users
$admins = get_users(array('role' => 'administrator'));
//Get editor role users
$editors = get_users(array('role' => 'editor'));
/* Combine editor and admin roles users and loop over
final array to collect admin and editor user ids */
$finalDatausers = array_merge($admins,$editors);
foreach($finalDatausers as $finalDatauser){
$admineditorIds[] = $finalDatauser->ID;
}
$admineditorIds = array_unique($admineditorIds);
//Get admin and editor posts
$admineditorquery = array(
'posts_per_page' => 5,
'author__in' => $admineditorIds,
);
$admineditorpostswpquery = new WP_Query($admineditorquery);
$admineditorposts = $admineditorpostswpquery->posts;
//create new empty query and populate it with the other two
$wp_query = new WP_Query();
// combining posts from author query and admineditor query to single query
$wp_query->posts = array_merge($authorposts,$admineditorposts);
//populate post_count count for the loop to work correctly
$wp_query->post_count = $admineditorpostswpquery->post_count + $authorpostswpquery->post_count;
while($wp_query->have_posts()) : $wp_query->the_post(); ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> <br>
<?php endwhile;
wp_reset_postdata();
?>