I have a list of posts on my website, what I'm trying to do is to wrap them alphabetically from A-Z by title to get a glossary like this:
A.
Apple
B.
Banana
C.
Carotts
D.
E.
F.
G.
Grenada
and so on untill letter z.
I want the letter to be displayed even if there's no post.
and i want to wrap results inside this structure :
<div class="group_letter">
<div class="letter">A</div>
<div class="post">Apple</div>
</div>
<div class="group_letter">
<div class="letter">B</div>
<div class="post">Banana</div>
</div>
here is what I've got so far :
<?php
$letter=' ';
query_posts( array ( 'post_type' => 'auteurs', 'orderby' => 'title', 'order' => 'ASC' ) );
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php
$title=get_the_title();
$initial=strtoupper(substr($title,0,1));
if($initial!=$letter) {
echo "<div>$initial</div>";
$letter=$initial;
}
echo "<div class='post'>" . $title. "</div>";
?>
<?php endwhile; endif; wp_reset_query(); ?>
here is the result :
<div class='letter'>A</div>
<div class='post'>Apple</div>
<div class='letter'>B</div>
<div class='post'>Banana</div>
<div class='letter'>C</div>
<div class='post'>carotts</div>
<div class='letter'>G</div>
<div class='post'>Grenanda</div>
I have 2 problems :
- Empty letters are not displayed.
- I can't find a way to wrap my groups inside
group_letter
div
.
</div>