anulik anulik - 1 month ago 8
PHP Question

Wordpress posts ordering by alphabetical for each letter

I need to display all posts ordering by

post_title ACS
, like this:

A
animal
angel
apple
C
cat
cinema
crime
F
friday
fire
K
kill
king
.................


and so on

So if there is no posts which titles are starting with G, the G will not be shown or displayed as letter separator like above.
Can anybody help?

Answer

I'd run a query to get all the posts ordered by post title as you usually would using get_posts. I would then loop through these and use substr to get the first letter of each post title. Make it uppercase. Create a new array. Check if the letter exists as a key in the array (array_key_exists). Add the key if needed and put the post inside. Following this process gives you an easy to manage array sorted by letter. Is there an easier way? Probably, but this will work.

Here is the code to achieve it:

<?php

$posts = get_posts(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
);

$letter_keyed_posts = array();

if ( $posts ) {
    foreach ( $posts as $post ) {
        $first_letter = strtoupper( substr( $post->post_title, 0, 1 ) );

        if ( ! array_key_exists( $first_letter, $letter_keyed_posts ) ) {
            $letter_keyed_posts[ $first_letter ] = array();
        }

        $letter_keyed_posts[ $first_letter ][] = $post;
    }
}

Use $letter_keyed_posts to output the content in the format you need.