douqiao1413 2018-01-20 16:36
浏览 8

如何列出帖子并按字母顺序包装?

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 :

  1. Empty letters are not displayed.
  2. I can't find a way to wrap my groups inside group_letter div.
</div>
  • 写回答

2条回答 默认 最新

  • douwei1904 2018-01-20 17:23
    关注

    Sorry, postin TV from phone, so may be not displaying properly

    Firstly, you have to create an array of all alphabets.

    $alph = array('A', 'B', 'C',.... 'Z'); 
    
    
    
    <
    
    ?php 
    $title=get_the_title(); 
    foreach($alph as $key) {
    // add while loop here
    initial=strtoupper(substr($title,0,1));
    if($initial!=$key) {
    echo '<div class="group_letter">';
    echo "<div>$key</div>";
    }else{
    
    echo "<div class='post'>" . $title. "</div>";
    }
    echo "</div>";
    // end while loop here 
    }
    ?>
    
    评论

报告相同问题?