[英]How to show only posts with certain category in wordpress theme?
我想知道是否有办法将此代码更改为仅显示来自 wordpress 中创建的特定类别的帖子。现在它显示每一个最近的帖子。 假设我将在 wordpress 中创建“新闻”类别,并且我希望这段代码仅显示新闻帖子。
感谢帮助
<?php
if( have_posts() ){
while( have_posts() ){
the_post();
get_template_part( 'template-parts/content', 'koncert');
}
}
?>
您可以覆盖 wordpress 使用的常规查询并创建自定义查询;
https://developer.wordpress.org/reference/classes/wp_query/
通常,虽然只是显示一个类别,但您只需打开类别 slug,如果您的模板具有正确的存档页面,它将显示该类别的帖子。
如果不使用类似于下面的内容。 您可以进一步优化您的搜索参数,例如上面链接中定义的帖子数量和帖子类型。
<?php
//refine your query to the category you desire either a slug(example below) or category id
$args = array(
'category_name' => 'my_category_slug',
);
//create the query using the arguments
$query = new WP_Query($args);
?>
//create the loop to show the posts
<?php if($query->have_posts()): ?>
<?php while($query->have_posts()): $query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<div><?php the_content(); ?></div>
<?php endwhile; ?>
<?php endif; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.