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:
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(); ?>
You could do something like this:
Finally got it thanks to this link: http://pastebin.com/b4WGrMhD