如何在WordPress中仅显示特定分类下的文章?

在WordPress中,你可以使用WP_Query类来调用指定分类下的文章。以下是一个示例代码:,,``php,,`,,在上面的代码中,你需要将'cat' => 1中的1`替换为你想要的分类ID。你可以根据需要自定义显示文章的数量和模板部分。这段代码会查询指定分类下的文章,并在循环中输出文章的标题、链接和摘要。如果没有找到任何文章,它将显示"没有找到任何文章"的消息。

在WordPress中调用指定分类下的文章,可以通过多种方法实现,以下是详细的步骤和代码示例:

如何在WordPress中仅显示特定分类下的文章?

WordPress调用指定分类下的文章

方法一:使用query_posts()函数

1、基本用法

<ul>
<?php query_posts('cat=1&showposts=5'); // cat是要调用的分类ID, showposts是需要显示的文章数量 ?>
<?php while (have_posts()) : the_post(); ?>
	<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>

2、解释

cat=1:这里的数字“1”是你要调用的分类ID。

showposts=5:这里表示要显示的文章数量为5篇。

方法二:使用WP_Query

1、基本用法

如何在WordPress中仅显示特定分类下的文章?

$args = array(
	'cat' => 1, // 分类ID
	'posts_per_page' => 5 // 显示文章数量
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
	echo '<ul>';
	while ($the_query->have_posts()) {
		$the_query->the_post();
		echo '<li><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></li>';
	}
	echo '</ul>';
	wp_reset_postdata();
}

2、解释

cat:设置要查询的分类ID。

posts_per_page:设置要显示的文章数量。

常见问题与解答

1、如何在首页列出所有分类及其对应的文章?

代码示例

<?php $cats = get_categories(); ?>
<?php foreach ($cats as $cat) { ?>
	<h3><?php echo $cat->name; ?></h3>
	<ul class="sitemap-list">
		<?php query_posts('cat=' . $cat->term_id . '&showposts=5'); ?>
		<?php while (have_posts()) : the_post(); ?>
			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
		<?php endwhile; wp_reset_query(); ?>
	</ul>
<?php } ?>

解释:这段代码首先获取所有的分类,然后对每个分类进行循环,显示分类名称和其对应的文章列表。

2、如何调用某个分类下的文章数量?

如何在WordPress中仅显示特定分类下的文章?

方法一:使用内置函数

<?php $postts = get_posts('numberposts=-1&category=分类id1,分类id2,分类id3'); ?>
<?php echo count($postts); ?>

方法二:使用get_category_by_slug()函数

<?php echo get_category_by_slug('category-name')->count; ?>

方法三:使用get_category()函数

<?php echo get_category(cat_ID)->count; ?>

方法四:使用wp_list_categories()函数

<?php echo strip_tags(wp_list_categories('include=3&hide_empty=0&use_desc_for_title=0&echo=0&show_count=1&style=none&hierarchical=0&title_li=')); ?>

解释:这些方法可以帮助你获取特定分类下的文章数量,可以根据具体需求选择合适的方法。

小伙伴们,上文介绍了“WordPress调用指定分类下的文章”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。