WordPress分类页多分类文章加载异常问题求助
问题描述
我给文章分配了对应分类,但当部分文章同时属于多个分类时,代码出现异常却没有报错,网站只会加载Cat1下的文章。文章的分类分配情况如下:
Post1 - Cat1 Post2 - Cat2 Post3 - Cat1,Cat3,Cat4 Post4 - Cat3 Post5 - Cat4
以下是我在category.php中使用的代码,它在文章只属于单个分类时正常运行,但多分类场景下完全失效:
<?php global $post; $category = get_the_category($post->ID); $category = $category[0]->cat_ID; $myposts = get_posts( array( 'numberposts' => -1, 'offset' => 0, 'category__in' => array($category), 'post_status'=>'publish', 'order'=>'ASC' ) ); foreach($myposts as $post) : setup_postdata($post); ?> <a href="<?php the_permalink() ?>"><?php echo substr(get_the_title(),0,55); ?></a> <?php endforeach; ?> <?php wp_reset_query(); ?>
问题根源
问题出在这段代码上:
$category = get_the_category($post->ID); $category = $category[0]->cat_ID;
get_the_category()会返回当前文章所属的所有分类组成的数组,但你直接取了数组的第一个元素$category[0],也就是只拿到了第一个分类的ID。当文章属于多个分类时,你只把第一个分类ID传给了category__in参数,自然只会加载该分类下的文章,完全忽略了其他分类。
修复代码
把文章所属的所有分类ID提取出来,组成数组再传给category__in即可,同时注意修正重置数据的函数:
<?php global $post; $categories = get_the_category($post->ID); // 提取所有分类ID到数组中 $category_ids = array(); foreach($categories as $cat) { $category_ids[] = $cat->cat_ID; } $myposts = get_posts( array( 'numberposts' => -1, 'offset' => 0, 'category__in' => $category_ids, // 传入所有分类ID数组 'post_status'=>'publish', 'order'=>'ASC' ) ); foreach($myposts as $post) : setup_postdata($post); ?> <a href="<?php the_permalink() ?>"><?php echo substr(get_the_title(),0,55); ?></a> <?php endforeach; ?> <?php wp_reset_postdata(); // 用wp_reset_postdata()替代wp_reset_query(),因为get_posts不需要重置主查询 ?>
额外说明
wp_reset_postdata()才是搭配get_posts()的正确重置函数,wp_reset_query()是给query_posts()用的,前者只恢复原始的$post对象,更贴合当前场景。- 修改后,当文章属于多个分类时,会加载所有这些分类下的文章,符合多分类场景的需求。
内容的提问来源于stack exchange,提问作者user3362364
相关产品推荐
相关产品推荐

