Search code examples
phpwordpresswordpress-admin

Why is my custom User View column not sorting A-Z?


I have added a custom column to my Users table in WordPress called Security Answer. I wanted to make this column sortable so I ended up with this code:

function trucklesoft_my_sortable_cake_column( $columns ) {
    $columns['security_answer'] = 'Security Answer';

    return $columns;
}
add_filter( 'manage_users_sortable_columns', 'trucklesoft_my_sortable_cake_column' );

I can now click on the column heading and it appears to do some kind of sort but it is not working.

It is a text based column and some items in the column are empty but I am expecting it to sort A-Z fashion or Z-A fashion but it won't.

How do I implement the sorting logic?


Solution

  • Your code only register the column as sortable, so the admin table headers include the necessary markup.

    But the sorting logic is not implemented. You would need something like this:

    add_action( 'pre_get_users', 'trucklesoft_security_orderby' );
    function trucklesoft_security_orderby( $query ) {
        if( ! is_admin() || ! current_user_can( 'edit_user' ) )
            return;
    
        $orderby = $query->get( 'orderby');
    
        if( 'security_answer' == $orderby ) {
            $query->set('meta_key','security_answer');
            $query->set('orderby','meta_value');
        }
    }
    

    It's been a while since I did WP, so you may need to adjust the code a bit. And I'm assuming your "security_answer" is indeed a custom postmeta.