i’m listing all posts of my custom post type “person” alphabetically sorted by the custom field last_name
on a page.
How would i insert a divider (e.g. an image of the letter) before a letter range starts?
Here’s what i’m trying to do:
Update:
Here’s the code i’m using:
<ul class="list-ensemble">
<?php query_posts('post_type=person&post_status=publish&meta_key=last_name&orderby=meta_value&order=ASC');
if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<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>
2 Answers
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
).