order by second word in title?

I have full names as title posts and want to order it by the surname.

How could i do this with wordpress?

in PHP it would be along the lines of –

 SELECT * from posts ORDER BY SUBSTR(LTRIM(post_title), LOCATE(' ',LTRIM(post_title)))

current code getting people category is;

$args = array(
    'posts_per_page'=>50,
    'cat'=> '39,-41',
    'orderby'=>'title',
    'order'=>'ASC',
);
query_posts($args);

how can i get that second word order?

best, Dan.

2 Answers
2

There is a filter, ‘posts_orderby’, which allows you to specify your own ORDER BY clauses. In your case, the code would look something like this:

add_filter( 'posts_orderby', 'order_by_surname' );

function order_by_surname( $orderby, $query ) {

    // first you should check to make sure sure you're only filtering the particular query
    // you want to hack. return $orderby if its not the correct query;

    return "ORDER BY SUBSTR(
        LTRIM({$wpdb->posts}.post_title), 
        LOCATE(' ',LTRIM({$wpdb->posts}.post_title)))";

}

Leave a Comment