Woocommerce 如何从订单对象中获取元值

Woocommerce how to get meta value from the order object

我正在尝试从 wc_order 获取自定义元数据字段。我必须澄清一下,我不是 php 的专业人士,我尝试了很多方法来获取字段,其中:

但是其中 none 有效。我有这个 订单 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
        )

)

我正在尝试获取以下 user_instagram 值:order > meta_data[3] > current_data > value

有人知道获取方法吗?

编辑

我正在尝试添加 lty_user_instagram 字段。这是负责做这件事的函数。

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' ) ;
  }
}

我要编辑的插件是 Lottery for Woocommerce by FantasticPlugins (class -lty-order-handler.php)

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.

您可以使用以下方式获取您的元数据:

$order_id = 12345;

$order = wc_get_order($order_id);

1- 使用 $order->get_meta():

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

2- 使用 get_post_meta():

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

3-使用 get_post_meta($order_id):

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

4- 使用 $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>";