programing

Woocommerce - 주문 품목의 가격과 수량을 가져옵니다.

kingscode 2023. 4. 1. 14:17
반응형

Woocommerce - 주문 품목의 가격과 수량을 가져옵니다.

Woocommerce 2.6.8을 사용해도 문서SO에 기재된 주문 항목 데이터 정보를 얻을 수 없습니다.

제가 원하는 것은 Line Item의 가격과 수량입니다.이것은 다음과 같이 간단하게 할 수 있습니다.

$order = new WC_Order( $order_id );
$order_items = $order->get_items();
 foreach ($order_items as $items_key => $items_value) {  
           echo $items_value['name']; //this works
           echo $items_value['qty']; //this doesn't work
           echo $items_value[item_meta][_qty][0]; //also doesn't work
           echo $items_value['line_total']; //this doesn't work
   }

반품된 상품을 자세히 살펴보기

Array
(
[1] => Array
    (
        [name] => Sample Product 1
        [type] => line_item
        [item_meta] => 
        [item_meta_array] => Array
            (
                [1] => stdClass Object
                    (
                        [key] => _qty
                        [value] => 1
                    )

                [2] => stdClass Object
                    (
                        [key] => _tax_class
                        [value] => 
                    )

                [3] => stdClass Object
                    (
                        [key] => _product_id
                        [value] => 8
                    )

                [4] => stdClass Object
                    (
                        [key] => _variation_id
                        [value] => 0
                    )

                [5] => stdClass Object
                    (
                        [key] => _line_subtotal
                        [value] => 50
                    )

                [6] => stdClass Object
                    (
                        [key] => _line_total
                        [value] => 50
                    )

                [7] => stdClass Object
                    (
                        [key] => _line_subtotal_tax
                        [value] => 0
                    )

                [8] => stdClass Object
                    (
                        [key] => _line_tax
                        [value] => 0
                    )

                [9] => stdClass Object
                    (
                        [key] => _line_tax_data
                        [value] => a:2:{s:5:"total";a:0:{}s:8:"subtotal";a:0:{}}
                    )

            )

    )

)

이것은 모두 문서화된 Woocommerce 메서드를 사용하고 있습니다.필요한 정보가 여기에 저장되어 있는 이유는 무엇입니까?item_meta_array?

제가 그 정보를 어떻게 얻을 수 있는지 아는 사람 있나요?

루프를 통해 루프를 실행하는 조잡한 해킹 대신 문서화된 방법을 사용하는 것이 바람직합니다.item_meta_array제가 찾는 열쇠를 찾을 때까지요

뭔가 확실한 걸 놓치고 있는 것 같아요

업데이트(WooCommerce 3+용)

이제 코드에는 다음과 같은 (및 ) 메서드를 대신 사용할 수 있습니다.

## For WooCommerce 3+ ##

// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id ); 

// Iterating through each "line" items in the order      
foreach ($order->get_items() as $item_id => $item ) {

    // Get an instance of corresponding the WC_Product object
    $product        = $item->get_product();

    $active_price   = $product->get_price(); // The product active raw price

    $regular_price  = $product->get_sale_price(); // The product raw sale price

    $sale_price     = $product->get_regular_price(); // The product raw regular price

    $product_name   = $item->get_name(); // Get the item name (product name)

    $item_quantity  = $item->get_quantity(); // Get the item quantity

    $item_subtotal  = $item->get_subtotal(); // Get the item line total non discounted

    $item_subto_tax = $item->get_subtotal_tax(); // Get the item line total tax non discounted

    $item_total     = $item->get_total(); // Get the item line total discounted

    $item_total_tax = $item->get_total_tax(); // Get the item line total  tax discounted

    $item_taxes     = $item->get_taxes(); // Get the item taxes array

    $item_tax_class = $item->get_tax_class(); // Get the item tax class

    $item_tax_status= $item->get_tax_status(); // Get the item tax status

    $item_downloads = $item->get_item_downloads(); // Get the item downloads

    // Displaying this data (to check)
    echo 'Product name: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. number_format( $item_total, 2 );
}

업데이트: 또한 다음과 같은 다양한 흥미로운 옵션을 사용하여 주문 항목 데이터를 가져올 수 있습니다.

// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id ); 

// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item) {
     ## Option: Including or excluding Taxes
     $inc_tax = true; 

     ## Option: Round at item level (or not)
     $round   = false; // Not rounded at item level ("true"  for rounding at item level)

     $item_cost_excl_disc = $order->get_item_subtotal( $item, $inc_tax, $round ); // Calculate item cost (not discounted) - useful for gateways.

     $item_cost_incl_disc = $order->get_item_total( $item, $inc_tax, $round ); // Calculate item cost (discounted) - useful for gateways.

     $item_tax_cost       = $order->get_item_tax( $item, $inc_tax, $round ); // Get item tax cost - useful for gateways.

      $item_Line_subtotal = $order->get_line_subtotal( $item, $inc_tax, $round ); // Get line subtotal - not discounted.

     $item_Line_total     = $order->get_line_total( $item, $inc_tax, $round ); // Get line total - discounted

     $item_Line_tax       = $order->get_line_tax( $item ); // Get line tax

     $form_line_subtotal  = $order->get_formatted_line_subtotal( $item, $tax_display = '' ) // Gets line subtotal - formatted for display.
}

@Casper의 코멘트 덕분입니다.


또한 다음 방법을 사용하여 순서 항목 데이터를 보호되지 않은 배열로 가져오거나 특정 메타 키에서 특정 중첩 또는 사용자 정의 메타 데이터 값을 가져올 수 있습니다.

// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id ); 

// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item ) {
    $order_item_data      = $item->get_data(); // Get WooCommerce order item meta data in an unprotected array
    print_r( $order_item_data ); // display raw data

    $item_meta_data = $item->get_meta_data(); // Get order item nested and custom meta data in an unprotected array
    print_r( $item_meta_data ); // display raw data

    $item_value     = $item->get_meta('meta_key'); // Get specific order item custom or nested meta data value from a meta_key
    print_r( $item_value ); // display raw data (can be a string or an array)
}

이 코드는 테스트되어 동작합니다.

방법get_item_meta()는 폐지되어 에 의해 대체되었습니다.이것은 메서드가 아닌 일부 파라미터를 가진 함수입니다.

/** Parameters summary
 * @param mixed $item_id
 * @param mixed $key
 * @param bool $single (default: true)
 * @return mixed
 */
wc_get_order_item_meta( $item_id, $key, $single = true );

이전 버전의 woocommerce(2.4에서2.6.x)

WC_Abstract_order 메서드를 사용하여 주문 메타데이터(품목 수량과 총 금액)를 얻을 수 있습니다.

코드는 다음과 같습니다.

// Getting the order object "$order"
$order = wc_get_order( $order_id );
// Getting the items in the order
$order_items = $order->get_items();
// Iterating through each item in the order
foreach ($order_items as $item_id => $item) {
    // Get the product name
    $product_name = $item['name'];
    // Get the item quantity
    $item_quantity = $order->get_item_meta($item_id, '_qty', true);
    // Get the item line total
    $item_total = $order->get_item_meta($item_id, '_line_total', true);

    // Displaying this data (to check)
    echo 'Product name: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. $item_total;
}

이 코드는 테스트되어 완전하게 기능하고 있습니다.

레퍼런스:클래스 WC_Abstract_Order 메서드

아이템 가격은 다음에서 얻을 수 있습니다.order아래 코드로 이의를 제기하다

$order->get_item_total( $item );

주문 클래스의 woocommerce Line 항목에 대해서는, 이 메뉴얼을 참조해 주세요.여기 있습니다

총 주문 비용은 총 금액으로 문의하시면 됩니다.product_id를 사용하여 단일 항목 비용을 가져오려면

$_product = wc_get_product( $product_id );
$Price = $_product->get_price();

아니면 이렇게 해도 돼.

$price = get_post_meta( get_the_ID(), '_regular_price', true);
$price = get_post_meta( get_the_ID(), '_sale_price', true);

이것은 주문 시 가격이 아닌 오늘 제품 가격을 받습니다.단가 10으로 주문하고 단가를 변경하면 새로운 가격을 받을 수 있습니다.주문은 여전히 이전 "원래" 주문 가격을 유지하고 있습니다.

언급URL : https://stackoverflow.com/questions/40711160/woocommerce-getting-the-order-item-price-and-quantity

반응형