以下是一个完整的WordPress循环标签代码
<?php
// 获取分类ID为2的分类信息
$category = get_category(2);
if ($category) {
// 获取分类名称
$category_name = $category->name;
// 获取分类链接
$category_link = get_category_link($category->term_id);
// 获取分类文章总数
$category_count = $category->category_count;
// 查询该分类下最新2篇文章(修正数量为2)
$args = array(
'cat' => 2,
'posts_per_page' => 2, // 修复:改为2篇
'orderby' => 'date',
'order' => 'DESC'
);
$query = new WP_Query($args);
// 显示分类信息
if ($query->have_posts()) {
echo '<ul class="post-list">';
// 分类信息只显示一次(移到循环外)
echo '<li>
<article class="article-list">
<header class="category-widget-header">
<a href="' . esc_url($category_link) . '"> // 修复:动态链接
<span class="category-title">'
. esc_html($category_name) .
'</span>
<span class="post-count">'
. number_format_i18n($category_count) . // 修复:移除多余点号
'</span>
</a>
</header>';
// 文章循环
while ($query->have_posts()) {
$query->the_post();
?>
<div class="category-latest-article">
<h3 class="entry-title entry-title-small">
<?php if (0 === $query->current_post) : // 仅在第一篇显示Latest ?>
<span class="latest-category-post">Latest : </span>
<?php endif; ?>
<a href="<?php the_permalink(); ?>"> // 修复:移除PHP标签嵌套
<?php the_title(); ?>
</a>
</h3>
</div>
<?php
}
echo '</article>
</li>
</ul>';
} else {
echo '<p>该分类下没有文章</p>';
}
// 重置查询
wp_reset_postdata();
} else {
echo '<p>指定的分类不存在</p>';
}
?>
版权声明:如发现本站有涉嫌抄袭侵权/违法违规的内容请联系客服!





