Arrange and separate posts

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.