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?

Read More

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.

Related posts

Leave a Reply

2 comments

  1. 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)))";
    
    }
    
  2. Your first example is an SQL query, there is no native WordPress function that does this.

    So that leaves you with some PHP options, explode it, str_word_count, along with sort (or ksort) to then arrange the array alphabetically.

    This is a very odd way to use this type of data, it should be in a meta box, since you basically have to hack the query in your case to get what you want.