1

When attempting to sort my media library uploads by author's name, it appears that WordPress will only sort by author ID ( http://example.com/wp-admin/upload.php?mode=list&orderby=author&order=desc )

Is this the intended behavior, a bug, or an oversight? It seems pretty useless to sort by author ID, I would much rather sort by first and/or last name.

1 Answer 1

1

Order by the author's display name:

This is most likely by design, because the only information about the author in the wp_posts table is the author ID.

We can join it with the wp_users table to get more information about the user and then modify the order accordingly.

Here's an example how we can order by the display name:

/**
 * Modify the author sorting of the media library uploads (mode=list), 
 * use 'display_name' instead of 'post_author'. 
 *
 * @see http://wordpress.stackexchange.com/a/184501/26350
 */
add_action( 'load-upload.php', function()
{
    add_filter( 'posts_clauses', function( $clauses, $q )
    {
        if(    $q->is_main_query()
            && 'list'   === filter_input( INPUT_GET, 'mode'    )
            && 'author' === filter_input( INPUT_GET, 'orderby' )
        ) {
            global $wpdb;

            // Join part:
            $clauses['join']    .= " LEFT JOIN {$wpdb->users} u 
                ON u.ID = {$wpdb->posts}.post_author ";

            // Orderby part:
            $clauses['orderby'] = str_replace( 
                "{$wpdb->posts}.post_author",
                " u.display_name", 
                $clauses['orderby'] 
            );
        }
        return $clauses;
    }, 10, 2 );
});

The first- and last names are stored in the wp_usermeta table, so you would need to adjust the SQL query for that, but note that these fields could both be empty. The display name, on the other hand, is always set, afaik.

1
  • I think there is a missing comma on line 19. Commented Apr 17, 2015 at 18:36

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.