skip to Main Content

I’m trying to get the COST of a line item in the WC order backend. (Seen in the attached image:enter image description here

Online I’ve read that I can do this, but all that seems to do is print out my line item total. I can’t seem to find a cost function. Any ideas? Thanks!

    $orderLineItems = $order->get_items();

    /* @var $order_item WC_Order_Item_Product */
    foreach ($orderLineItems as $item_id => $order_item) {

      var_dump($order_item->get_total());

    }

2

Answers


  1. You can get the cost by dividing the total with the quantity.

    echo 'Cost: '.$order_item->get_subtotal() / $order_item->get_quantity();
    echo '<br />';
    echo 'Subtotal: '.$order_item->get_subtotal();
    echo '<br />';
    echo 'Total: '.$order_item->get_total();
    
    Login or Signup to reply.
  2. Try this
    You can get the cost by order item.

    // Order Id 
      $order_id = 502;
    // Get an instance of the WC_Order object (same as before)
    $order = wc_get_order( $order_id );
    // Iterating through each WC_Order_Item_Product objects
    foreach ($order->get_items() as $item_id => $order_item):
       $item_name    = $order_item->get_name(); // Name of the product
        $quantity     = $order_item->get_quantity();  // quantity of the product
        $tax_class    = $order_item->get_tax_class();
        $line_subtotal     = $order_item->get_subtotal(); // Line subtotal (non discounted)
        $line_subtotal_tax = $order_item->get_subtotal_tax(); // Line subtotal tax (non discounted)
        $line_total        = $order_item->get_total(); // Line total (discounted)
        $line_total_tax    = $order_item->get_total_tax(); // Line total tax (discounted)
    
    endforeach;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search