Group Posts by Custom Field – Alphabetically
-
Hello everyone,
I’m piecing together a custom employee directory using a custom post type called “professionals” and a taxonomy to group them called “titles”. I’ve been organizing everything based on a custom field for each employee’s last name (custom field key is ‘prof_lastname’).
I’d like to list all employees alphabetically, grouped underneath each letter, based on that key. I found some code here that allows you to do it based on post title, and am just wondering if there’s a way to modify this to use a custom field instead.
More specifically, here’s the section I’m trying to work with as it currently exists on my site:
<?php $querystr = " SELECT * FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE $wpdb->posts.post_type = 'professionals' AND $wpdb->term_taxonomy.taxonomy = 'titles' AND $wpdb->posts.post_status = 'publish' AND $wpdb->postmeta.meta_key = 'prof_lastname' ORDER BY $wpdb->postmeta.meta_value ASC "; $pageposts = $wpdb->get_results($querystr, OBJECT); ?> <?php if ($pageposts): ?> <?php while ($my_query->have_posts()) : $my_query->the_post(); $this_char = strtoupper(mb_substr($post->post_title,0,1,'UTF-8')); if ($this_char != $last_char) { $last_char = $this_char; echo '<a name="section-'.$last_char.'"></a><br class="clear" /><h2>'.$last_char.'</h2>'; } ?> <article class="professional-entry" id="entry-<?php echo $last_char ?>"> <div><strong><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></strong></div> <div><?php $terms = get_the_terms( $post->ID , 'titles' ); foreach( $terms as $term ) { print $term->name; unset($term); } ?></div> <div><a href="mailto:<?php echo get_post_meta($post->ID, 'prof_email', true); ?>"><?php echo get_post_meta($post->ID, 'prof_email', true); ?></a></div> </article> <?php endwhile; ?> <?php endif; ?>
I’m querying posts within my custom post type, getting the meta_key “prof_lastname” for each entry, shortening it down to the first letter and displaying various things based off of that. The code to group them by letter is still doing it by post title (so right now that means alphabetically by first name) but I’d like it organized by that meta_key (by last name).
Let me know if this is too confusing. I’ve been going nuts with it myself. Thanks in advance.
- The topic ‘Group Posts by Custom Field – Alphabetically’ is closed to new replies.