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 
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答