Display usernames in Woocommerce Admin orders list custom column

女生的网名这么多〃 提交于 2019-12-03 21:41:45

Updated: The right meta_key to get the user ID in woocommerce orders is _customer_user, so:

$user_id = get_post_meta( $post_id, '_customer_user', true );

Or you can use $the_order global object as:

global $the_order;
$user_id = $the_order->get_customer_id();

After you can get the WordPress userdata from this user ID:

$user_data = get_userdata( $userid );

echo 'Username: ' . $user_data->user_login . "<br>";
echo 'User email: ' . $user_data->user_email . "<br>";
echo 'User roles: ' . implode(', ', $user_data->roles) . "<br>";
echo 'User ID: ' . $user_data->ID . "<br>";
echo 'User full name: ' . $user_data->last_name .  ", " . $user_data->first_name . "<br>";

So in your code:

// Adding a custom new column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_column_eldest_players', 20 );
function custom_column_eldest_players($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['skb-client'] = __( 'Oudste Speler','theme_domain');
        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for the column
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    if ( 'skb-client' != $column ) return;

    global $the_order;

    // Get the customer id
    $user_id = $the_order->get_customer_id();

    if( ! empty($user_id) && $user_id != 0) {
        $user_data = get_userdata( $user_id );
        echo $user_data->user_login; // The WordPress user name
    }
    // Testing (to be removed) - Empty value case
    else
        echo '<small>(<em>Guest</em>)</small>';
}

Code goes in function.php file of your active child theme (or active theme). Tested and works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!