Arrange and separate posts

On a particular archive page I’ve created, I’m listing a number of posts by post name and they’re listed in alphabetical order. Is there away to have them separated even further?

As in all posts starting with “A” are grouped and have a heading of “A”, then all posts starting with “B” are grouped and have a heading of “B”, etc.

1 Answer
1

You can do some tricky thing with PHP. Here is the algorithm you could use.

  1. Query posts to get posts as alphabetical order.
  2. for/while loop starts.
  3. $t = Get first character of the title string.
  4. $temp = '' empty string.
  5. if $t != $temp echo $t.
  6. set $t = $temp.
  7. endfor/endwhile.

Hope it make sense. The main idea is you check the first character of the title to a temp variable. When their is a mismatch it will print the character. So you will get a character printed out when you transit to '' to A, A to B and so on.. 🙂


Finally got some time. Here is a very basic code example with get_posts()

<?php

    $posts = get_posts($args);

        $temp = '';
    foreach($posts as $post):
        $title = get_the_title();
        $first_letter = strtoupper(substr($title, 0, 1)); 
        if($temp != $first_letter){
            echo $first_letter;
            $temp = $first_letter;  
        }
        ?>
            <a href="https://wordpress.stackexchange.com/questions/76437/<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php
    endforeach;

?>

This code show the letter if their is an change of first letter of title. Make sure you sort it alphabetically when calling get_posts(). Hope you get the idea.

Leave a Comment