I cannot seem to find where WP_Query adds the orderby clause to a SQL query.

I am using this code:

function wpd_team_taxonomy_queries( $query ) {
if ( !is_admin() && $query->is_tax( 'team' ) && $query->is_main_query() ) {
    $query->set( 'orderby',  " SUBSTRING_INDEX( t.name, ' ', -1 ) "); 
    $query->set( 'order', 'ASC' );
}add_action( 'pre_get_posts', 'wpd_team_taxonomy_queries' );

This works well apart from one particular taxonomy type, which I am debugging. I can see that WP_Query orderby parameter is set as above, but I cannot see in any of the queries from the DEBUG plugin or the Query Monitor plugin where the SUBSTRING_INDEX( t.name, ' ', -1 ) code is added to a SQL query.

Neither for the correctly ordering results nor the one that is not ordered.

How would I find where this particular SQL query is built for orderby to debug this ?

1 Answer 1


You can't pass SQL directly as query parameters. The only valid values for orderby are covered in the docs for WP_Query.

If you want to directly modify the SQL, you need to use the posts_* filters, in this case posts_orderby.

  • Thanks Milo. I did that and it's working. The original code was a cut and paste from stack overflow. I wonder if orderby accepted SQL in times past.
    – Kolleyk
    Commented Feb 16, 2019 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.