【发布时间】:2020-03-05 18:10:03
【问题描述】:
我想显示同一类别的多个帖子,但我只想打印一次类别名称。具有相同类别的帖子将在一次打印的类别名称下打印。 下面是我想要的输出图片:
这是我的代码
<?php
$args = array('post_type' => 'books_section', 'posts_per_page' => -1 );
$the_query = new WP_Query($args);
while ($the_query -> have_posts()): $the_query -> the_post();
?>
<div class="col-3 col-sm-3 col-md-2 col-lg-1 col-xl-1">
<div class="img-category w-75">
<?php
$category = get_the_category();
if($category[0]){
$thumbnail = the_post_thumbnail('thumbnail');
echo "<img height='50' width='100' alt='' src='$thumbnail'>";
}
?>
<!-- <img height="50" width="100" alt="" src="<?php the_field('category_image'); ?>"> -->
</div>
</div>
<div class="col-9 col-sm-9 col-md-10 col-lg-11 col-xl-11">
<h5 class="text-capitalize">
<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>
</h5>
</div>
<div class="col-12 col-sm-12 col-md-6 col-lg-3 col-xl-3 mt-5">
<a class="text-decoration-none" href="<?php the_field('amazon_book_link');?>" target="">
<div class="book-hover">
<?php the_post_thumbnail('full'); ?>
<!-- <img alt="" src="./assets/images/Layer 40@1X.png" class="" height="350" width="250"> -->
</div>
<h6 class="text-capitalize font-weight-bold text-center mt-2 book-title"><?php the_title(); ?></h6>
<?php if( get_field('audio_book') == 'yes' ): ?>
<h6 class="text-capitalize font-weight-bold text-center mt-2 book-type">Audio Book</h6>
<?php endif; ?>
<?php if( get_field('comng_soon') == 'yes'): ?>
<h6 class="text-capitalize font-weight-bold text-center mt-2 book-type">Coming Soon</h6>
<?php endif; ?>
</a>
</div>
<?php endwhile; ?>
我现在得到的结果是循环正在分别打印所有帖子及其类别名称,但我只需要一次类别名称并打印该特定类别的所有帖子。 然后循环应该打印新类别的其他帖子。 请帮帮我。
【问题讨论】:
-
我正在为这本书部分使用自定义帖子类型。
-
在循环前创建一个变量,起始值为-1;如果不相等,内部循环将类别与该变量进行比较,显示类别名称并更新变量,因此名称将显示到下一个类别。
-
@Triby 你能帮我做吗?因为我试过了,但没有成功。
-
我不知道
$category的值,请尝试并编辑问题以包含您的尝试,我会帮助您。
标签: php wordpress advanced-custom-fields custom-post-type