loop – Group search results by post type, but having a unique heading for each section?
Question
I’ve been struggling to make it work. This code works and returns search results separated for each post type, however I would like to have a unique heading for each section and style it, currently it only shows the name of those post type.. not looking pretty and user friendly.
Here is the code I’m using:
<?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, 'windows' => 0, 'android' => 0, 'game' => 0, 'web' => 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-parts/content', 'archive' ); ?>
<?php endif; ?>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php else :
_e( 'Sorry, nothing has been found.' );
?>
0
2 months
2023-04-07T17:56:51-05:00
2023-04-07T17:56:51-05:00 0 Answers
0 views
0
Leave an answer