我正在设计类别页面。我有一个循环显示当前类别的子类别。对于每个子类别,我想显示最新文章的链接。目前,即使所显示的文章不在该类别中,所有子类别的链接也是相同的。我究竟做错了什么?
<?php
$cat_id = get_query_var('cat');
$categories = get_categories(array( 'parent' => $cat_id));
if(count($categories) > 0):
foreach($categories as $cat):
$args = array(
'numberposts' => 1,
'offset' => 0,
'category' => $cat->cat_ID,
'orderby' => 'ID',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true );
$the_query = new WP_Query( $args );
$the_query->the_post();
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$recent['title'] = get_the_title();
$recent['id'] = get_the_ID();
wp_reset_postdata();
endwhile;
endif;
wp_reset_postdata(); ?>
<div class="media category-list">
<div class="media-body">
<div class="details">
<h3><a href="<?php echo get_category_link($cat->cat_ID); ?>"><?php echo $cat->name; ?></a></h3>
<p><?php echo $cat->description; ?></p>
</div>
<dl>
<dt>Article Total:</dt><dd><?php echo $cat->count; ?></dd>
<dt>Last Article:</dt><dd><a href="<?php echo get_permalink($recent["id"]); ?>"><?php echo substr($recent["title"], 0, 48).'...'; ?></a></dd>
</dl>
</div>
</div>
<?php endforeach;
endif; ?>
答案 0 :(得分:0)
您似乎在get_posts
中使用WP_Query
个参数。
category
和numberposts
不是WP_Query
get_posts
,内部已转换为cat
和posts_per_page
WP_Query
中传递这些参数时,它不起作用。但是当你在WP_Query
中传递get_posts
个参数时,它可以工作;)所以更新的参数结构是
$args = array(
'posts_per_page' => 1,
'offset' => 0,
'cat' => $cat->cat_ID,
'orderby' => 'ID',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
另请使用此
更新您的查询$the_query = new WP_Query( $args );
//$the_query->the_post();
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$recent['title'] = get_the_title();
$recent['id'] = get_the_ID();
// wp_reset_postdata();
endwhile;
endif;
wp_reset_postdata();
the_post
只能在您确定查询有帖子后调用一次。
wp_reset_postdata
保存整个查询的数据。所以需要在while循环结束时不在while循环内部。