In a similar fashion to my jQuery Quickie post series, here is where I post some quick code that I used in a recent WP project that I find useful enough to want to use in the future. Sometimes it will be flashy, and other times it will be something really simple. It all depends on the need I’m trying to fill.

Today, its pretty simple. What were’re going to take a look at is how to sort your post by the last word in your wp_title() string. Here is the code.

$posts = get_posts(array('post_type' => 'post'));
$lastname = array();
foreach( $posts as $key => $post ) {
 $lastname[$key] = array_pop( explode( ' ', $post->title ) );
array_multisort( $lastname, SORT_ASC, $posts );

Now after viewing it, let’s begin by breaking it down!

$posts: this is a variable we’re using to store the returned posts objects from the get_posts method.

$lastname: this is an empty array we’ll be using to create our sort criteria for $posts

$key => $post: the $key variable is providing a named reference for the post objects in the $lastname array, and $posts is used to get the value to store in the $lastname array

array_pop: this is a php function that takes the last array position value and returns it. Ex: echo array_pop([‘hello’, ‘hi’]) ; //returns hi

explode: this takes a string and turns it into array based on the separator condition defined. Here is it is a space.

array_multisort: This is pretty cool. This php function takes one array, sorts it to your criteria, and then does the same thing to another specified array. In this case its our friendly holder variable $posts