Sort posts alphabetically by custom field value, insert divider between different letters

Try this:

<ul class="list-ensemble">
<?php query_posts('post_type=person&post_status=publish&meta_key=last_name&orderby=meta_value&order=ASC'); 
$current_letter="";
if ( have_posts() ) while ( have_posts() ) : the_post();
    $last_name = get_post_meta( $post->ID, 'last_name', true );
    $letter = strtolower( substr( $last_name, 0, 1 ) );
    if ( $letter != $current_letter ) {
        $current_letter = $letter; ?>
        <li class="letter">
            <img src="https://wordpress.stackexchange.com/questions/10561/<?php echo $letter; ?>.jpg" alt="<?php echo $letter; ?>" title="<?php echo $letter; ?>">
        </li>
    <?php } ?>
    <li data-id="<?php the_ID(); ?>">
        <a href="https://wordpress.stackexchange.com/questions/10561/<?php the_permalink(); ?>" class="ensemble-single-link">
            <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'thumbnail' ); } ?>
        </a>
    </li>
<?php endwhile; // end of the loop. ?>
</ul>

For each post in the loop, it retrieves the last_name postmeta field (this won’t add any queries to the page because WordPress caches the postmeta), then checks the first letter of it. If it’s a new letter, it outputs a list element with an image named after the letter (e.g. f.jpg).

Leave a Comment