Sort Custom Post Type by Custom Field

How can you sort a custom post type by a custom field in WordPress? I’m trying to figure out a way to echo a custom field called ‘State’ alphabetically and place the custom post type links called employees under each of their respect states.

So it would look like this:

Read More

Alabama

  • Appleseed, Johnny
  • Chamber, Pete

Florida

  • Miller, Sam
  • Stark, Amy

    I know how to write the basic loop for a custom post type but I’m not sure how to sort under a custom field belonging to that post type alphabetically.

    <?php $query = new WP_query ( array( 'post_type'=> 'employees', 'meta_key'=> 'state', 
     'orderby'=> 'meta_value', 'order' => 'DESC'));
       while ( $query -> have_posts() ) : $query -> the_post(); ?>
    <?php echo get_post_meta($post->ID, 'state', true); ?>
     <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php
    endwhile;   
    wp_reset_query();  ?>
    

Related posts

Leave a Reply

2 comments

  1. You could do something like this:

    <?php $query = new WP_query ( array( 'post_type'=> 'employees', 'meta_key'=> 'state', 'orderby'=> 'meta_value', 'order' => 'DESC'));
      while ( $query -> have_posts() ) : $query -> the_post(); ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
      <?php
    endwhile;   
    wp_reset_query();  ?>
    
  2. Finally got it thanks to this link: http://pastebin.com/b4WGrMhD

    <?php $employeesQuery = new WP_Query(array('post_type' => 'employees', 'meta_key' => 'state', 'orderby' => 'meta_value', 'order' => 'ASC', 'posts_per_page' => '-1')); ?>
      <?php $prevltr = ""; ?>
        <?php if(have_posts()) { while ( $employeesQuery->have_posts() ) { $employeesQuery->the_post(); ?>
                <?php $state = get_post_meta($post->ID, 'state', true); ?>
                <?php $curltr = $state; ?>
                <?php if($curltr != $prevltr) : ?>
                    <a name="section-<?php echo $curltr ?>"></a><br class="clear" /><h4><?php echo $curltr; $prevltr = $curltr; ?></h4>
                <?php endif; ?>
    
                <article class="employee-entry" id="entry-<?php the_title_attribute(); ?>">
    
                    <div><strong><a href="<?php the_permalink() ?>" title="<?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>
    
                </article>
    
    <?php }} ?>