Get customer id from order id in WooCommerce

I want to retrieve the "mycred" balance of a customer via an order using WP ALL Export to export the customer balance based on orders to a spreadsheet. It's actually pretty simple. I can get the order id but not the customer id

Here's what I do to check if I can get the client ID:

function get_customeruserid($value)
{
  global $woocommerce, $post;

  $order = new WC_Order($post->ID);
  $order_id = $order->get_order_number();

  $customer = new WC_Customer($post->ID);
  $user_id = $customer->get_ID();

  $value = $user_id;
  return $value;
}

      

This returns 0.

However, I can easily get the order number by doing the following:

function get_customerorderid($value)
{
  global $woocommerce, $post;

  $order = new WC_Order($post->ID);
  $order_id = $order->get_order_number();

  $value = $order_id;
  return $value;
}

      

This returns the customer order number which is great but only half the battle. Now I want the customer ID, so I call the mycred balance function to display my balance.

Any ideas? I am new to php and probably very bad.

+3


source to share


3 answers


You can use order number to get corresponding customer id using database query, google wordpress meta query



+2


source


To get the user id from the order id you can use many ways, here are 2 of them:

In WooCommerce 2.5 to 3.0+, you can use like this: get_post_meta()

function get_customerorderid(){
    global $post;
    $order_id = $post->ID;

    // Get the user ID
    $user_id = get_post_meta($order_id, '_customer_user', true);

    return $user_id;
}

      



In WooCommerce 3.0+ you can use WC_Order class methods like this:

function get_customerorderid(){
    global $post;
    $order_id = $post->ID;

    // Get an instance of the WC_Order object
    $order = wc_get_order($order_id);

    // Get the user ID from WC_Order methods
    $user_id = $order->get_user_id(); // or $order->get_customer_id();

    return $user_id;
}

      

+11


source


For anyone looking to specifically add the client's mycred balance from ORDER to the CSV sheet in WP All Export, this is the bit of code I used. Thanks for helping to solve the problem.

While editing the ORDER export in WP ALL EXPORT, add a new data object and click on it and "Export value returned by PHP function", then add the following function to the code editor:

function all_export_mycred($balance)
{
    global $woocommerce, $post;

    $order = new WC_Order($post->ID);
    $user_id = $order->get_user_id( );

    $balance = mycred_get_users_balance( $user_id );

            return $balance;

    }

      

Then be sure to add "all_export_mycred" to the php return field.

+5


source







All Articles