I’m using WordPress to generate a list of posts.
The outputted HTML looks something like this:
<ul>
<!-- HERE -->
<li id="post-258" class="grid_6 convenience-stores" data-id="post-258">
<h1><a href="/?p=258">Local Store #2</a></h1>
</li>
<li id="post-109" class="grid_6 convenience-stores" data-id="post-109">
<h1><a href="/?p=109">Local Store #1</a></h1>
</li>
<!-- HERE -->
<li id="post-107" class="grid_6 where-to-buy" data-id="post-107">
<h1><a href="/?p=107">Supermarket #2</a></h1>
</li>
<li id="post-105" class="grid_6 where-to-buy" data-id="post-105">
<h1><a href="/?p=105">Supermarket #1</a></h1>
</li>
</ul>
I use the following PHP code to generate this:
<?php
while (have_posts()) : the_post();
$category = get_the_category();
$class = $category[0]->slug;
?>
<li data-id="post-<?php the_ID(); ?>" class="grid_6 <?php echo $class; ?>" id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php the_post_thumbnail('small');?>
<?php endif; ?>
</li>
<?php endwhile; ?>
You can see I have 2 different categories / HTML class names “where-to-buy” & “convenience-stores“.
Now, what I would like to do is “break” the loop when the category changes.
So, at the point in the above HTML where I have marked <!-- HERE -->
, I was hoping I could add an <h2>
element to signify a heading for the next set of posts.
Is this possible?
And if so, how do I achieve this?
Many thanks for your help.
Keep track of the previous value of
$class
(eg.$prevClass
) and check against this in your loop. Presumably the records are already in$class
order?Note, however, that with your current HTML markup it is not valid to simply output an
H2
in the places you have marked – these will need to be inside anli
. Or, close and open theul
.Having multiple
H1
s is not necessarily a good idea either, although several wordpress themes do seem to follow this structure. If you are using HTML5 andarticle
/section
then this might be OK.H2
s might be more appropriate here.