Additional column in WooCommerce admin order list with the user login

155 Views Asked by At

I need to add a custom column "Customer" in the backend of WooCommerce orders list.

Here is some code that add additional columns to admin orders list and displays the user ID:

add_filter( 'manage_edit-shop_order_columns', 'add_new_order_admin_list_column' ); 
function add_new_order_admin_list_column( $columns ) { 
    $columns['user_id'] = 'Kunde'; 
    return $columns; 
} 

add_action( 'manage_shop_order_posts_custom_column', 'add_new_order_admin_list_column_content' ); 
function add_new_order_admin_list_column_content( $column ) { 
    global $post; 
    if ( 'user_id' === $column ) { 
        $order = wc_get_order( $post->ID ); 
        echo $order->get_user_id(); 
    } 
}

How to display the "User login" instead of the user ID?

1

There are 1 best solutions below

0
On

To display the "user login" in a custom column on admin orders list, you can use the following:

// Add a custom column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column', 20 );
function custom_shop_order_column($columns)
{
    $sorted_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $sorted_columns[$key] = $column;
        if( $key ==  'order_status' ){
            $sorted_columns['customer'] = __( 'Customer', 'woocommerce');
        }
    }
    return $sorted_columns;
}

// Display content for a custom column in admin orders list
add_action( 'manage_shop_order_posts_custom_column' , 'custom_shop_order_column_content', 20, 2 );
function custom_shop_order_column_content( $column, $post_id )
{
    if ( $column === 'customer' ) {
        // Get the user ID from the order
        $user_id  = get_post_meta( $post_id, '_customer_user', true );

        if ( $user_id > 0 ) {
            // Get the WP_User object from the user ID
            $user = get_userdata( $user_id );
                
            // Display the "User login"
            echo '<span>'. $user->user_login .'</span>';
        } else {
            // For guest users
            echo '<em>'.__('Guest user').'</em>';
        }
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.