1

I'm trying to get a custom meta data field from wc_order. I have to clarify that I'm not a pro in php and I have tried many ways to get field, with:

  • get_meta()
  • get_meta_data()
  • get_post_meta( $order_id )
  • and so on...

But none of them have worked. I have this order object:

(
    [refunded_line_items:protected] => 
    [status_transition:protected] => 
    [meta_data:protected] => Array
        (
            [0] => WC_Meta_Data Object
                (
                    [current_data:protected] => Array
                        (
                            [id] => 4126
                            [key] => is_vat_exempt
                            [value] => no
                        )

                    [data:protected] => Array
                        (
                            [id] => 4126
                            [key] => is_vat_exempt
                            [value] => no
                        )

                )

            [1] => WC_Meta_Data Object
                (
                    [current_data:protected] => Array
                        (
                            [id] => 4140
                            [key] => lty_ticket_ids_in_order
                            [value] => Array
                                (
                                    [0] => 321
                                )

                        )

                    [data:protected] => Array
                        (
                            [id] => 4140
                            [key] => lty_ticket_ids_in_order
                            [value] => Array
                                (
                                    [0] => 321
                                )

                        )

                )

            [2] => WC_Meta_Data Object
                (
                    [current_data:protected] => Array
                        (
                            [id] => 4141
                            [key] => lty_lottery_ticket_created_once
                            [value] => 1
                        )

                    [data:protected] => Array
                        (
                            [id] => 4141
                            [key] => lty_lottery_ticket_created_once
                            [value] => 1
                        )

                )
            // I want to get this meta object
            [3] => WC_Meta_Data Object
                (
                    [current_data:protected] => Array
                        (
                            [id] => 4142
                            [key] => user_instagram
                            // I want to access this value!
                            [value] => @nomames
                        )

                    [data:protected] => Array
                        (
                            [id] => 4142
                            [key] => user_instagram
                            [value] => @nomames
                        )

                )

            [4] => WC_Meta_Data Object
                (
                    [current_data:protected] => Array
                        (
                            [id] => 4146
                            [key] => _new_order_email_sent
                            [value] => true
                        )

                    [data:protected] => Array
                        (
                            [id] => 4146
                            [key] => _new_order_email_sent
                            [value] => true
                        )

                )

        )

    [data:protected] => Array
        (
            [parent_id] => 0
            [status] => on-hold
            [currency] => MXN
            [version] => 5.6.0
            [prices_include_tax] => 
            [date_created] => WC_DateTime Object
                (
                    [utc_offset:protected] => 0
                    [date] => 2021-09-07 19:33:31.000000
                    [timezone_type] => 1
                    [timezone] => +00:00
                )

            [date_modified] => WC_DateTime Object
                (
                    [utc_offset:protected] => 0
                    [date] => 2021-09-07 19:33:31.000000
                    [timezone_type] => 1
                    [timezone] => +00:00
                )

            [discount_total] => 0
            [discount_tax] => 0
            [shipping_total] => 0
            [shipping_tax] => 0
            [cart_tax] => 0
            [total] => 10.00
            [total_tax] => 0
            [customer_id] => 5
            [order_key] => wc_order_U5dJhlrUaeLjN
            [billing] => Array
                (
                    [first_name] => Ezequiel2
                    [last_name] => 
                    [company] => 
                    [address_1] => 
                    [address_2] => 
                    [city] => 
                    [state] => 
                    [postcode] => 
                    [country] => 
                    [email] => e@gmail.com
                    [phone] => 
                )

            [shipping] => Array
                (
                    [first_name] => 
                    [last_name] => 
                    [company] => 
                    [address_1] => 
                    [address_2] => 
                    [city] => 
                    [state] => 
                    [postcode] => 
                    [country] => 
                    [phone] => 
                )

            [payment_method] => bacs
            [payment_method_title] => Transferencia bancaria directa
            [transaction_id] => 
            [customer_ip_address] => 187.190.122.134
            [customer_user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
            [created_via] => checkout
            [customer_note] => 
            [date_completed] => 
            [date_paid] => 
            [cart_hash] => 9b73a20812d33740408a871a8f83a474
        )

    [items:protected] => Array
        (
        )

    [items_to_delete:protected] => Array
        (
        )

    [cache_group:protected] => orders
    [data_store_name:protected] => order
    [object_type:protected] => order
    [id:protected] => 320
    [changes:protected] => Array
        (
        )

    [object_read:protected] => 1
    [extra_data:protected] => Array
        (
        )

    [default_data:protected] => Array
        (
            [parent_id] => 0
            [status] => 
            [currency] => 
            [version] => 
            [prices_include_tax] => 
            [date_created] => 
            [date_modified] => 
            [discount_total] => 0
            [discount_tax] => 0
            [shipping_total] => 0
            [shipping_tax] => 0
            [cart_tax] => 0
            [total] => 0
            [total_tax] => 0
            [customer_id] => 0
            [order_key] => 
            [billing] => Array
                (
                    [first_name] => 
                    [last_name] => 
                    [company] => 
                    [address_1] => 
                    [address_2] => 
                    [city] => 
                    [state] => 
                    [postcode] => 
                    [country] => 
                    [email] => 
                    [phone] => 
                )

            [shipping] => Array
                (
                    [first_name] => 
                    [last_name] => 
                    [company] => 
                    [address_1] => 
                    [address_2] => 
                    [city] => 
                    [state] => 
                    [postcode] => 
                    [country] => 
                    [phone] => 
                )

            [payment_method] => 
            [payment_method_title] => 
            [transaction_id] => 
            [customer_ip_address] => 
            [customer_user_agent] => 
            [created_via] => 
            [customer_note] => 
            [date_completed] => 
            [date_paid] => 
            [cart_hash] => 
        )

    [data_store:protected] => WC_Data_Store Object
        (
            [instance:WC_Data_Store:private] => WC_Order_Data_Store_CPT Object
                (
                    [internal_meta_keys:protected] => Array
                        (
                            [0] => _parent_id
                            [1] => _status
                            [2] => _currency
                            [3] => _version
                            [4] => _prices_include_tax
                            [5] => _date_created
                            [6] => _date_modified
                            [7] => _discount_total
                            [8] => _discount_tax
                            [9] => _shipping_total
                            [10] => _shipping_tax
                            [11] => _cart_tax
                            [12] => _total
                            [13] => _total_tax
                            [14] => _customer_id
                            [15] => _order_key
                            [16] => _billing
                            [17] => _shipping
                            [18] => _payment_method
                            [19] => _payment_method_title
                            [20] => _transaction_id
                            [21] => _customer_ip_address
                            [22] => _customer_user_agent
                            [23] => _created_via
                            [24] => _customer_note
                            [25] => _date_completed
                            [26] => _date_paid
                            [27] => _cart_hash
                            [28] => _customer_user
                            [29] => _order_key
                            [30] => _order_currency
                            [31] => _billing_first_name
                            [32] => _billing_last_name
                            [33] => _billing_company
                            [34] => _billing_address_1
                            [35] => _billing_address_2
                            [36] => _billing_city
                            [37] => _billing_state
                            [38] => _billing_postcode
                            [39] => _billing_country
                            [40] => _billing_email
                            [41] => _billing_phone
                            [42] => _shipping_first_name
                            [43] => _shipping_last_name
                            [44] => _shipping_company
                            [45] => _shipping_address_1
                            [46] => _shipping_address_2
                            [47] => _shipping_city
                            [48] => _shipping_state
                            [49] => _shipping_postcode
                            [50] => _shipping_country
                            [51] => _shipping_phone
                            [52] => _completed_date
                            [53] => _paid_date
                            [54] => _edit_lock
                            [55] => _edit_last
                            [56] => _cart_discount
                            [57] => _cart_discount_tax
                            [58] => _order_shipping
                            [59] => _order_shipping_tax
                            [60] => _order_tax
                            [61] => _order_total
                            [62] => _payment_method
                            [63] => _payment_method_title
                            [64] => _transaction_id
                            [65] => _customer_ip_address
                            [66] => _customer_user_agent
                            [67] => _created_via
                            [68] => _order_version
                            [69] => _prices_include_tax
                            [70] => _date_completed
                            [71] => _date_paid
                            [72] => _payment_tokens
                            [73] => _billing_address_index
                            [74] => _shipping_address_index
                            [75] => _recorded_sales
                            [76] => _recorded_coupon_usage_counts
                            [77] => _download_permissions_granted
                            [78] => _order_stock_reduced
                        )

                    [meta_type:protected] => post
                    [object_id_field_for_meta:protected] => 
                    [must_exist_meta_keys:protected] => Array
                        (
                        )

                )

            [stores:WC_Data_Store:private] => Array
                (
                    [coupon] => WC_Coupon_Data_Store_CPT
                    [customer] => WC_Customer_Data_Store
                    [customer-download] => WC_Customer_Download_Data_Store
                    [customer-download-log] => WC_Customer_Download_Log_Data_Store
                    [customer-session] => WC_Customer_Data_Store_Session
                    [order] => WC_Order_Data_Store_CPT
                    [order-refund] => WC_Order_Refund_Data_Store_CPT
                    [order-item] => WC_Order_Item_Data_Store
                    [order-item-coupon] => WC_Order_Item_Coupon_Data_Store
                    [order-item-fee] => WC_Order_Item_Fee_Data_Store
                    [order-item-product] => WC_Order_Item_Product_Data_Store
                    [order-item-shipping] => WC_Order_Item_Shipping_Data_Store
                    [order-item-tax] => WC_Order_Item_Tax_Data_Store
                    [payment-token] => WC_Payment_Token_Data_Store
                    [product] => WC_Product_Data_Store_CPT
                    [product-grouped] => WC_Product_Grouped_Data_Store_CPT
                    [product-variable] => WC_Product_Variable_Data_Store_CPT
                    [product-variation] => WC_Product_Variation_Data_Store_CPT
                    [shipping-zone] => WC_Shipping_Zone_Data_Store
                    [webhook] => WC_Webhook_Data_Store
                    [report-revenue-stats] => Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore
                    [report-orders] => Automattic\WooCommerce\Admin\API\Reports\Orders\DataStore
                    [report-orders-stats] => Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore
                    [report-products] => Automattic\WooCommerce\Admin\API\Reports\Products\DataStore
                    [report-variations] => Automattic\WooCommerce\Admin\API\Reports\Variations\DataStore
                    [report-products-stats] => Automattic\WooCommerce\Admin\API\Reports\Products\Stats\DataStore
                    [report-variations-stats] => Automattic\WooCommerce\Admin\API\Reports\Variations\Stats\DataStore
                    [report-categories] => Automattic\WooCommerce\Admin\API\Reports\Categories\DataStore
                    [report-taxes] => Automattic\WooCommerce\Admin\API\Reports\Taxes\DataStore
                    [report-taxes-stats] => Automattic\WooCommerce\Admin\API\Reports\Taxes\Stats\DataStore
                    [report-coupons] => Automattic\WooCommerce\Admin\API\Reports\Coupons\DataStore
                    [report-coupons-stats] => Automattic\WooCommerce\Admin\API\Reports\Coupons\Stats\DataStore
                    [report-downloads] => Automattic\WooCommerce\Admin\API\Reports\Downloads\DataStore
                    [report-downloads-stats] => Automattic\WooCommerce\Admin\API\Reports\Downloads\Stats\DataStore
                    [admin-note] => Automattic\WooCommerce\Admin\Notes\DataStore
                    [report-customers] => Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore
                    [report-customers-stats] => Automattic\WooCommerce\Admin\API\Reports\Customers\Stats\DataStore
                    [report-stock-stats] => Automattic\WooCommerce\Admin\API\Reports\Stock\Stats\DataStore
                    [product-tb-placeholder] => ET_Theme_Builder_Woocommerce_Product_Variable_Placeholder_Data_Store_CPT
                    [product-tb-placeholder-variation] => ET_Theme_Builder_Woocommerce_Product_Variable_Placeholder_Data_Store_CPT
                )

            [current_class_name:WC_Data_Store:private] => WC_Order_Data_Store_CPT
            [object_type:WC_Data_Store:private] => order
        )

)

I'm trying to get the following user_instagram value: order > meta_data[3] > current_data > value

Does someone know a way to get it?

Edit

I'm trying to add lty_user_instagram field. This is the function in charge of doing it.

public static function create_ticket_on_placing_order( $order_id, $product_id = false ) {

  if ( get_post_meta( $order_id , 'lty_lottery_ticket_created_once' , true ) ) {
    return ;
  }

  $order = wc_get_order( $order_id ) ;

  if ( ! is_object( $order ) ) {
    return ;
  }

  $user_id = $order->get_user_id() ;
  if ( ! $user_id ) {
    return ;
  }

  $user = get_user_by( 'ID' , $user_id ) ;

  if ( ! $user->exists() ) {
    return ;
  }

  $currency   = $order->get_currency() ;
  $ip_address = ! empty( $order->get_customer_ip_address() ) ? $order->get_customer_ip_address() : lty_get_ip_address() ;

  $ticket_ids = array() ;

  foreach ( $order->get_items() as $item ) {
    $product = $item->get_product() ;
    if ( ! is_object( $product ) || 'lottery' != $product->get_type() || ! $product->has_lottery_status( 'lty_lottery_started' ) ) {
      continue ;
    }

    // Validate product id.
    if ( $product_id && $product->get_id() != $product_id ) {
      continue ;
    }

    $answer          = '' ;
    $answers         = array() ;
    $is_valid_answer = 'no' ;

    if ( isset( $item[ 'lty_lottery_answers' ][ 0 ] ) ) {
      $question_answers = $product->get_answers() ;
      if ( array_key_exists( $item[ 'lty_lottery_answers' ][ 0 ] , $question_answers ) ) {
        $answer  = $question_answers[ $item[ 'lty_lottery_answers' ][ 0 ] ][ 'label' ] ;
        $answers = array(
          'label' => $question_answers[ $item[ 'lty_lottery_answers' ][ 0 ] ][ 'label' ] ,
          'key'   => $item[ 'lty_lottery' ][ 'answers' ] ,
          'valid' => $question_answers[ $item[ 'lty_lottery_answers' ][ 0 ] ][ 'valid' ]
            ) ;

        $is_valid_answer = $question_answers[ $item[ 'lty_lottery_answers' ][ 0 ] ][ 'valid' ] ;
      }
    }

    $args = array(
      'lty_user_id'      => $user->ID ,
      'lty_user_instagram' => "Here is where I want to ser order's user_instagram" ,
      'lty_product_id'   => $product->get_id() ,
      'lty_amount'       => $product->get_price() ,
      'lty_user_name'    => $user->user_login ,
      'lty_user_email'   => $user->user_email ,
      'lty_currency'     => $currency ,
      'lty_order_id'     => $order_id ,
      'lty_answer'       => $answer ,
      'lty_answers'      => $answers ,
      'lty_valid_answer' => $is_valid_answer ,
      'lty_ip_address'   => $ip_address ,
        ) ;
            
    $ticket_numbers = $product->get_ticket_numbers($item);
    if ( ! lty_check_is_array( $ticket_numbers ) ) {
      continue ;
    }

    foreach ( $ticket_numbers as $ticket_number ) {

      $args[ 'lty_ticket_number' ] = $ticket_number ;
      $ticket_ids[]                = lty_create_new_lottery_ticket( $args , array( 'post_parent' => $product->get_lottery_id() , 'post_status' => 'lty_ticket_pending' ) ) ;
    }
            
    if ( ! $product->is_manual_ticket() ) {
      // Update order item meta for automatic type.
      $item->add_meta_data( '_lty_lottery_tickets' , $ticket_numbers ) ;
      $item->add_meta_data( esc_html__( 'Ticket Number( s )' , 'lottery-for-woocommerce' ) , implode( ' , ' , $ticket_numbers ) ) ;
      $item->save() ;
    }

    //Unset metas on placing order.
    self::unset_metas_on_placing_order( $product , $order , $ticket_numbers ) ;
  }

  if ( lty_check_is_array( $ticket_ids ) ) {
    // Update custom order meta for ticket ids.
    update_post_meta( $order_id , 'lty_ticket_ids_in_order' , $ticket_ids ) ;
    update_post_meta( $order_id , 'lty_lottery_ticket_created_once' , '1' ) ;
  }
}

The plugin I'm trying to edit is Lottery for Woocommerce by FantasticPlugins (class-lty-order-handler.php)

Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • with `wc_get_order()` – Ezequiel S. Sandoval Sep 08 '21 at 04:13
  • 2
    When you say *"This is what I get on each case when I try to get $order metadata."*, what's the code you're trying? The one with `$args` doesn't even work. Provide your code i want to see the code with which you get the "data". – Ruvee Sep 08 '21 at 19:21
  • 1
    Also include the name of the plugin you use to store the metadata. – Ruvee Sep 08 '21 at 19:22
  • 2
    Please edit your question. Currently, your question is not reproducible, you're claiming that you're getting a result using a code snippet that doesn't even run because it's incorrect. You don't provide the name of the plugin you're using to store your metadata either. – Ruvee Sep 08 '21 at 19:43
  • I have edited question, let me know if there's something else I should add as info – Ezequiel S. Sandoval Sep 08 '21 at 20:41

1 Answers1

8
The following solutions have been fully tested on wordpress 5.8 and woocommerce 5+.
They're recommended, if you use update_post_meta to store your metadata as part of the order object.

Please keep in mind, if you're using third party plugins that store the metadata for you, then you may encounter discrepancies.

You could use the following ways to get your metadata:

$order_id = 12345;

$order = wc_get_order($order_id);

1- using $order->get_meta():

echo "<pre>";
print_r($order->get_meta('user_instagram'));
echo "</pre>";

2- using get_post_meta():

echo "<pre>";
echo get_post_meta($order->get_id(), 'user_instagram', true);
echo "</pre>";

3-using get_post_meta($order_id):

echo "<pre>";
print_r(get_post_meta($order_id)['user_instagram'][0]);
echo "</pre>";

4- using $order->get_meta_data():

echo "<pre>";
foreach ($order->get_meta_data() as $object) {
  $object_array = array_values((array)$object);
  foreach ($object_array as $object_item) {
    if ('user_instagram' == $object_item['key']) {
      print_r($object_item['value']);
      break;
    }
  }
}
echo "</pre>";
Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • I get my data dump when I `print_r($order)`, metadata prop is inside `$order` but let me try with you proposals and I'll let you know if it some works – Ezequiel S. Sandoval Sep 08 '21 at 17:20
  • There's one particular thing and it is that `get_post_meta` doesn't get back all meta fields but this is because **user_instagram** is inserted into database after this function is executed... the only part where y can get it from is from `$order` object. – Ezequiel S. Sandoval Sep 08 '21 at 18:11
  • 2
    1- How do you save `user_instagram` as part of the order object to the data base? 2-`get_post_meta` is using order object. `$order->get_meta_data()`. I've tested all three of the functions above and they all work on my end. – Ruvee Sep 08 '21 at 18:15
  • `user_instagram` is a custom field in the checkout form, it's handled by a plugin. But when I get the **order** with `wc_get_order` the dump is the one that you see above and it includes the user instagram on it, but I'm not able to get that field yet. When I use `$order->get_meta_data()` it returns only one meta data field, the one with the **key** `is_vat_exempt`. If i use `get_post_meta` it gets the last metadata field I mention and another 20 keys. Will edit my question to show whats returned on each case – Ezequiel S. Sandoval Sep 08 '21 at 18:23
  • You can check **Edit 2** to know what's happening with different order methods you proposed to get meta. – Ezequiel S. Sandoval Sep 08 '21 at 18:37
  • #1 is the most future way of getting the order meta. Especially as WC is moving to custom order tables: https://github.com/woocommerce/woocommerce/wiki/High-Performance-Order-Storage-Upgrade-Recipe-Book#apis-for-gettingsetting-posts-and-postmeta – Uriahs Victor Jan 22 '23 at 00:30