Order by the results of a function with WP_query

@JasCav
Here is something to put you in the right direction.
Maybe someone can edit where needed.

// args  
$args = [
   'post_parent'    => $post->ID,
   'post_type'      => 'page',
   'posts_per_page' => 8,
   'paged'          => get_query_var( 'paged' ),
   'meta_key'       => 'team_school',
   'meta_value'     => $school_type,
   'orderby'        => 'wpse_last_word', //<-- make filter for ordering!
   'order'          => 'ASC'
];

// query
$the_query = new WP_Query( $args );


     add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
     {

       if( isset( $args['orderby'] ) && 'wpse_last_word' === $args['orderby'] )
       { 

       global $wpdb;       
       $orderby = " SUBSTRING_INDEX(  $wpdb->postmeta.meta_value, ' ', -1 ) "; 

       }

       return $orderby;

     }, PHP_INT_MAX, 2 );

Referenced from https://wordpress.stackexchange.com/a/198624/29133

Leave a Comment