jawittdesigns
4/14/2015 - 4:54 PM

Ignore "the" when ordering by post title

Ignore "the" when ordering by post title

function create_temp_column ($fields) {
    global $wpdb;
    $matches = 'A|An|The|La';
    $has_the = " CASE 
                 WHEN $wpdb->posts.post_title regexp( '^($matches)[[:space:]]' )
                 THEN trim(substr($wpdb->posts.post_title from 4)) 
                 ELSE $wpdb->posts.post_title 
                 END AS title2";
    if( $has_the ){
        $fields .= ( preg_match( '/^(\s+)?,/', $has_the ) ) ? $has_the : ", $has_the";
    }
    return $fields;
}

function sort_by_temp_column ($orderby) {
    $custom_orderby = " UPPER(title2)";
    if ( $custom_orderby ) {
        $orderby = $custom_orderby;
    }
    return $orderby;
}

add_filter( 'posts_fields','create_temp_column'); // Add the temporay column filter
add_filter( 'posts_orderby', 'sort_by_temp_column' ); // Add the custom order filter
				
$query = new WP_Query( array( 'post_type' =>'post' ) ); // Your custom query
				
remove_filter( 'posts_fields','create_temp_column' ); // Remove the temporary column filter
remove_filter( 'posts_orderby', 'sort_by_temp_column' ); // Remove the temporary order filter