Skip to content

Instantly share code, notes, and snippets.

@IacopoC
Created November 20, 2017 10:47
Show Gist options
  • Save IacopoC/2647ec8a1176bec882ecd3059610a911 to your computer and use it in GitHub Desktop.
Save IacopoC/2647ec8a1176bec882ecd3059610a911 to your computer and use it in GitHub Desktop.
Order custom query by last word
<?php
$args = [
'posts_per_page' => 10,
'post_type' => 'speaker',
'meta_key' => 'speaker-front-page',
'meta_value' => '1',
'orderby' => 'customq_last_word', //<-- Custom ordering
'order' => 'ASC'
];
// query
$the_query = new WP_Query( $args );
// On functions.php
add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( 'customq_last_word' === $q->get( 'orderby' ) && $get_order = $q->get( 'order' ) )
{
if( in_array( strtoupper( $get_order ), ['ASC', 'DESC'] ) )
{
global $wpdb;
$orderby = " SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) " . $get_order;
}
}
return $orderby;
}, PHP_INT_MAX, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment