Skip to content

Instantly share code, notes, and snippets.

@elpuas
Created December 1, 2022 18:16
Show Gist options
  • Save elpuas/72f3cf358f1a1048010451ea35b90fe8 to your computer and use it in GitHub Desktop.
Save elpuas/72f3cf358f1a1048010451ea35b90fe8 to your computer and use it in GitHub Desktop.
Order by the last word of the string
/**
* Order by last word in title.
*
* @param string $orderby orderby
* @param object $query data
*
* @link https://wordpress.stackexchange.com/questions/1003/order-posts-by-last-word-in-title
*
* @return string
*/
function elpuas_orderby_last_word( $orderby, $query ) {
global $wpdb;
if ( 'elpuas_last_word' === $query->get( 'orderby' ) ) {
$orderby = "SUBSTRING_INDEX({$wpdb->posts}.post_title, ' ', -1)";
}
return $orderby;
}
add_filter( 'posts_orderby', 'elpuas_orderby_last_word', PHP_INT_MAX, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment