唯一的方法是对它们进行计数或通过WP\\u查询(重新)请求它们。我想我更喜欢第一种解决方案,因为它不太复杂。
<?php if (have_posts()) : ?>
<?php
// We change the definition of the array to be able to store the count of each post_type
$types = array(\'post\' => 0, \'videos\' => 0, \'graphics\' => 0, \'photos\' => 0);
while (have_posts()) {
the_post();
// We check that only allowed post_type are counted
if (array_key_exists(get_post_type(), $types)) {
$types[get_post_type()]++;
}
}
?>
<?php foreach ($types AS $type => $nb_of_type) : ?>
<?php // We only show post_types that have at least one result ?>
<?php if ($nb_of_type > 0) : ?>
<div class="card">
<div class="card-header">
<h4><?= $type; ?></h4>
</div>
<div class="card-body">
<?php while (have_posts()) : the_post(); ?>
<?php if (get_post_type() === $type) : ?>
<?php get_template_part(\'template-part/content\', $type); ?>
<?php endif; ?>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>