Подтвердить что ты не робот

Получить элементы заказа и WC_Order_Item_Product в WooCommerce 3

Хорошо, читая об изменениях в WooCommerce 3. 0+, кажется, что вы больше не можете напрямую обращаться к этому классу, поэтому я предположил бы, что этот код нужно изменить, так как он выдает ошибку:

$order_item_id = 15;
$order_item = new WC_Order_Item_Product($order_item_id);
$return = $order_item->get_id() ? $order_item : false;

Но, смущающе, я не уверен, как изменить этот код, чтобы использовать правильные новые функции получения и установки в самой новой версии этого класса, которая больше не имеет конструкции. Как это сделать правильно? Я не вижу функции get для получения элемента заказа таким же образом, как указано выше.
https://docs.woocommerce.com/wc-apidocs/class-WC_Order_Item_Product.html

Может быть, я что-то упускаю здесь?

4b9b3361

Ответ 1

  Если вы используете метод get_id(), вы получите свой идентификатор элемента, который в вашем коде равен 15.

Получить идентификатор продукта:
Правильныйметод WC_Order_Item_Product для получения идентификатора продукта: get_product_id()

Получить идентификатор варианта:
Правильный метод WC_Order_Item_Product для получения идентификатора продукта: get_variation_id()

Получить идентификатор заказа
Правильныйметод WC_Order_Item_Product для получения идентификатора заказа: get_order_id()

Получить объект WC_Product
Правильныйметод WC_Order_Item_Product для получения объекта WC_Product: get_product()

Получить объект WC_Order
Правильныйметод WC_Order_Item_Product для получения объекта WC_order: get_order()

Получить и снять защиту данных и метаданных, используя WC_Data методы:
get_data()
get_meta_data()


Получить объект WC_Product из идентификатора позиции заказа:

$order_item_id = 15;
$item = new WC_Order_Item_Product($order_item_id);

// The product ID
$product_id = $item->get_product_id(); 

// The variation ID
$product_id = $item->get_variation_id(); 

// The WC_Product object
$product = $item->get_product(); 

// The quantity
$order_id = $item->get_quantity(); 

// The order ID
$order_id = $item->get_order_id(); 

// The WC_Order object
$order = $item->get_order(); 

// The item ID
$item_id = $item->get_id(); // which is your $order_item_id

// The product name
$product_name = $item->get_name(); // … OR: $product->get_name();

//Get the product SKU (using WC_Product method)
$sku = $product->get_sku();

Получить элементы заказа из объекта WC_Order (и использовать объект WC_product):

$order_id = 156; // The order_id

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

// The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
foreach( $order->get_items() as $item_id => $item ){
    //Get the product ID
    $product_id = $item->get_product_id();

    //Get the variation ID
    $product_id = $item->get_variation_id();

    //Get the WC_Product object
    $product = $item->get_product();

    // The quantity
    $product_name = $item->get_quantity();

    // The product name
    $product_name = $item->get_name(); // … OR: $product->get_name();

    //Get the product SKU (using WC_Product method)
    $sku = $product->get_sku();
}

Доступ к данным и пользовательским метаданным:

1) снятие защиты с WC_Order_Item_Product данных и пользовательских метаданных:

Вы можете использовать все WC_Order_Item_Product data методы или снять защиту данных с помощью WC_Data следующих методов:

$order_id = 156; // The order_id

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

// The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
foreach( $order->get_items() as $item_id => $item ){

    // Get the common data in an array: 
    $item_product_data_array = $item->get_data();

    // Get the special meta data in an array: 
    $item_product_meta_data_array = $item->get_meta_data();

    // Get the specific meta data from a meta_key: 
    $meta_value = $item->get_meta( 'custom_meta_key', true );

    // Get all additional meta data (formatted in an unprotected array)
    $formatted_meta_data = $item->get_formatted_meta_data( ' ', true );
}

2) Доступ к массиву все еще возможен (для обратной совместимости с устаревшими массивами) для непосредственного получения общих данных:

$order_id = 156; // The order_id

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

// The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
foreach( $order->get_items() as $item_id => $item ){


    $product_id    = $item['product_id']; // Get the product ID
    $variation_id  = $item['variation_id']; // Get the variation ID

    $product_name  = $item['name']; // The product name
    $item_qty      = $item['quantity']; // The quantity
    $line_subtotal = $item['line_subtotal'];  // The line subtotal
    $line_total    = $item['line_total'];  // The line subtotal

    // And so on ……
}

Как ссылка:

Ответ 2

WC_Order_Item_Product наследует от WC_Order_Item, у которого есть get_order_id(), поэтому вы можете получить идентификатор заказа с

$order_item->get_order_id();