问题主要是由于在处理文章时,从多个分类中获取的文章数量总和可能会超过设置的限制。虽然设置了每个分类下最多获取10篇文章,但这些文章可能在多个分类中重复出现,导致最终展示的文章总数超过了预期。
让我们分析一下代码的每一步:

1.获取所有分类:
$categories = get_the_category();
2.从每个分类中获取前10篇文章:
$rank_posts = get_posts(array(
"orderby" => "meta_value_num",
"meta_key" => "views",
"numberposts" => 10,
"category" => $category->term_id,
"post_status" => "publish"
));
3.将文章ID存储在数组中以去重:
foreach ($rank_posts as $rank_post) :
$unique_post_ids[$rank_post->ID] = true;
endforeach;
4.从唯一的文章ID中获取所有文章:
$args = array(
"post__in" => $unique_post_ids,
"post_status" => "publish",
"orderby" => "post__in",
"posts_per_page" => -1
);
$unique_posts = get_posts($args);
5.展示文章:
foreach ($unique_posts as $unique_post) :
setup_postdata($unique_post);
// 输出文章
endforeach;
问题所在:
每个分类中获取的文章是独立的,且可能有重复。如果一篇文章在多个分类中被选中,它只会在unique_post_ids数组中出现一次,但由于从不同分类中获取的文章总数可能达到或超过13篇(如你所见),因此最终展示的文章数量也会超过10篇。
解决方案:
为了确保最终展示的文章数量不会超过10篇,可以在将所有唯一文章存储到数组后,再对它们进行限制。这可以通过在获取所有文章之前对$unique_post_ids数组进行限制来实现。
更新代码如下:
<?php
global $post;
// 获取当前文章的所有分类
$categories = get_the_category();
// 用于存储唯一文章ID的数组
$unique_post_ids = array();
foreach ($categories as $category) :
// 获取当前分类下按“views”排序的前10篇文章
$rank_posts = get_posts(array(
"orderby" => "meta_value_num",
"meta_key" => "views",
"numberposts" => 10,
"category" => $category->term_id,
"post_status" => "publish"
));
foreach ($rank_posts as $rank_post) :
// 将文章ID添加到数组中
$unique_post_ids[$rank_post->ID] = true; // 使用键值对来去重
endforeach;
endforeach;
// 限制唯一文章ID的数量为10
$unique_post_ids = array_slice($unique_post_ids, 0, 10, true);
// 将唯一的文章ID从键名数组中提取出来
$unique_post_ids = array_keys($unique_post_ids);
// 获取所有唯一文章的信息
$args = array(
"post__in" => $unique_post_ids,
"post_status" => "publish",
"orderby" => "post__in",
"posts_per_page" => -1 // 确保获取所有文章
);
$unique_posts = get_posts($args);
foreach ($unique_posts as $unique_post) :
// 设置文章数据
setup_postdata($unique_post);
?>
<li><a href="<?php echo get_permalink($unique_post->ID); ?>" title="<?php echo esc_attr(get_the_title($unique_post->ID)); ?>"><?php echo get_the_title($unique_post->ID); ?></a></li>
<?php
endforeach;
// 重置文章数据
wp_reset_postdata();
?>
这个更新通过array_slice函数限制了$unique_post_ids数组的大小,确保最终展示的文章数量不会超过10篇。



发表评论