1

I have a custom post type that stores a couple of user IDs in postmeta.

I need to sort this column in the admin post list (edit.php). The column sorts correctly by its postmeta user ID, but I am displaying the user.display_name as content in that column. I'm not sure how to construct the SQL clauses to make this happen.

add_filter( 'posts_clauses', array( $this, 'sort_post_clauses' ), 10, 2 );
function sort_post_clauses( $clauses, $query ) {

    //Join user table onto the postmeta table
    $clauses[ 'join' ] .= " LEFT JOIN {$wpdb->users} ON {$wpdb->postmeta}.meta_value={$wpdb->users}.ID";
    $clauses[ 'orderby' ] = "{$wpdb->users}.display_name ";
    $clauses[ 'orderby' ] .= ( 'ASC' == strtoupper( $query->get( 'order' ) ) ) ? 'ASC' : 'DESC';

}

The 'join' clause above is incorrect.

The postmeta column 'some_user_id' exists in the postmeta table. I'm not sure how to form the join statement to get it available in the query.

I need the results sorted by user->display_name.

0

If I'm understanding your question correctly, I think you just want to sort your custom column by author, since by default this will sort by the ID. Untested, but can't see why it wouldn't work. The display value of the column shouldn't matter.

add_action( 'pre_get_posts', 'wpse_orderby_author_column' );
function wpse_orderby_author_column( $query ) {
    if( ! is_admin() )
        return;

    $orderby = $query->get('orderby');

    // Change my_custom_column to the name of your column
    if( 'my_custom_column' == $orderby ) {
        $query->set('orderby','author');
    }
}
  • I do also display the author column and it is sortable as well as filterable, but I am storing a user ID in postmeta to track interactions with the cpt and need to be able to sort it also. Problem is that I want to sort by display_name - not by user ID. – rwkiii Feb 2 '17 at 7:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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