wordpress - 如何在 Wordpress 中显示最后三个自定义帖子类型
问题描述
我非常清楚这个问题已经被问了一百万次,但我真的需要你的帮助,因为尽管遵循了所有建议,但我不能将自定义帖子类型的数量限制为显示为 3。这意味着,每次我创建新的自定义帖子类型(新的马拉松)时,循环都会将其添加到其他帖子类型。我想要的是我的循环只显示最后 3 场马拉松比赛。我认为指示 'posts_per_page' => 3 就足够了,但事实并非如此。
请帮忙!谢谢!
这是我的代码:
<?php
$the_query = new WP_Query( 'post_type=kinsta_marathon' );
array(
'post_type' => 'kinsta_marathon',
'post_status' => 'publish',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => 'slider',
'field' => 'slug',
'terms' => 'slider'
)
)
);
// The Loop!
if ($queryObject->have_posts()) {
?>
<?php
while ($queryObject->have_posts()) {
$queryObject->the_post();
?>
<div class="container mb-3 py-3">
<div class="row h-100 pl-3 rowcalendartop ">
<div class="container h-100">
<div class="row h-100">
<div class="col-1 py-0"><img class="logomarathoncalendar" src="<?php the_field('logo_marathon'); ?>" alt="logo-marathon"></div>
<div class="col-10 py-0 align-self-center"><h5 class="mb-0 align self-center"> <?php the_title(); ?></h5></div>
</div>
</div>
</div>
<div class="row rowcalendarbottom h-100 greysection py-3">
<div class="col-2 align-self-center"><h6 class="mb-0"><i class="fas fa-map-marker-alt iconslidermarathon mr-3"></i> <?php the_field('where_marathon'); ?></h6></div>
<div class="col-2 align-self-center"><h6 class="mb-0"><i class="fas fa-calendar iconslidermarathon mr-3"></i> <?php the_field('when_marathon'); ?></h6></div>
<div class="col-2 align-self-center"><h6 class="mb-0"><i class="fas fa-running iconslidermarathon mr-3"></i> <?php the_field('km_marathon'); ?></h6></div>
<div class="col-2 align-self-center"><h6 class="mb-0"><i class="fas fa-euro-sign iconslidermarathon mr-3 "></i> <?php the_field('marathon_price'); ?></h6></div>
<a href="<?php the_permalink(); ?>" target="_blank"><div class="col-2 align-self-center"><h5 class="mb-0 text-center"><i class="fas fa-arrow-right iconslidermarathon mr-3"></i></h6></div></a>
</div>
</div>
<?php
}
?>
<?php
}
?>
<!--end loop-->
解决方案
您没有将参数传递给 WP_Query,只是 post_type。将数组作为参数包含到 WP_Query 中,它将起作用。
$the_query = new WP_Query( array(
'post_type' => 'kinsta_marathon',
'post_status' => 'publish',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => 'slider',
'field' => 'slug',
'terms' => 'slider'
)
)
));
此外,您不需要if
包装循环。如果列表为空,它将不会处理循环,并且如果列表为空,则不会显示任何类型的消息,表明没有记录。
另一项更改是确保查询和循环的变量相同。您命名了查询变量$the_query
,但您正在循环访问$queryObject
.
// The Loop!
<?php
while ($the_query->have_posts()) {
$the_query->the_post();
?>
有关有用的示例,请参阅WordPress WP_Query 页面。