WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a custom post type called Employees where an employee's name is the post_title of each post.

I am trying to figure out how I would sort the post_title column by last name.

So for instance, if we have the following post entries:

1. Justin Bieber 2. Selena Gomez 3. Jessica Alba 4. Nicholas Cage

The query would contain the entire list of employees sorted by last name, so:

1. Jessica Alba 2. Justin Bieber 3. Nicholas Cage 4. Selena Gomez

Anybody? Thanks.

share|improve this question
up vote 2 down vote accepted

You could use usort(). Your callback function would need to determine the last names and sort by them.

So, for instance:

$args = array( 
    'post_type' = 'Employees',
$employees = get_posts( $args );
usort( $employees, 'wp91501_sort_employees' );

and then your callback might be:

function wp91501_sort_employees( $a, $b ) {

    // split the names into arrays
    $a_name = explode( ' ', $a->post_title );
    $b_name = explode( ' ', $b->post_title );

    // get the last name from the $x_name arrays
    $a_last_name = end( $a_name );
    $b_last_name = end( $b_name );

    if( $a_last_name == $b_last_name ) {
        return 0;
    return ($a_last_name < $b_last_name ) ? -1 : 1 ;

Note that this is a very simple comparison -- if the employee has a double last name with no hyphen (for instance, "John Smythe Jones") then it'll get sorted according to the very last part of the name (in the example, "Jones").

An easier option might be to enter the employees in the form 'LastName, FirstName', which would allow you to just sort by post_title ASC. But then you'd need to filter the_title if you wanted to display the title as 'FirstName LastName'.

share|improve this answer
Not sure if I'm implementing this right but before the usort, I print_r($employees) and it returns all entries, but after usort it just returns 1. – mousesports Mar 19 '13 at 17:40
Whoops, I wasn't calling usort() quite right. I've fixed the code above; the fix is to change $employees = usort( $employees, 'wp91501_sort_employees' ); to usort( $employees, 'wp91501_sort_employees' ); . Sorry for the confusion. – Pat J Mar 19 '13 at 17:49
Oh ya! Nice, works great. Thanks a lot :) – mousesports Mar 19 '13 at 17:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.