Sort Wordpress custom posts alphabetically

  • 11/11/2010

I recently used WordPress’s new custom post type functionality (WP3+) to get biographies and testimonials for each staff member of a community organization entered in. Then, to sort them by last name, I used an ugly-but-functional call to array_multisort:

$lastname = array();
$posts = get_posts( array( 'post_type' => 'staffer', 'numberposts' => 10 ) );

foreach( $posts as $key => $post ) {

    $lastname[$key] = array_pop( explode( ' ', $post->post_title ) );
array_multisort( $lastname, SORT_ASC, $posts );```

This is predicated on the assumption that each post of the custom `staffer` post type is named after the appropriate staffer, and the last name is the last word in the post title.

A better approach would be to build a more robust filter on the query_post hook that adds a $last_name variable to posts as they are retrieved, but that’s a battle for another day.