Search code examples
phpwordpresswoocommerceorderssubtotal

Extracting from formatted price the number for calculations in WooCommerce


I'm working on a custom invoice template with the plugin WooCommerce PDF Invoices & Packing Slips by Ewout Fernhout, and I faced with problem, when I want to create a more detailed product list on the invoice.

There is a foreach loop in the default template which shows all the products from the order:

$items = $this->get_order_items(); 

if( sizeof( $items ) > 0 ) : 

foreach( $items as $item_id => $item ) :

After that, I'd like to calculate the amount of discount in € and in % based on the $items. I dumped the content, and found that the product price is in $item['price'] (string(119)) and the original price is in the $item['product']->price (string(3)). I can echo the value of $item['price'], but when I want to get only the price from $item['price'] (for example from 250.00€) with substring, but it is useless, returns with nothing or the length value of the function. (With the second variable - $item['product']->price, I don't have issues)…

$price = $item['price'];
echo $price.'<br/>';
echo strlen($price).'<br/>';
echo substr($price,0,10).'<br/>';
echo strlen(trim(substr($price,0,10))).'<br/>';

It displays:

250.00€
119
10

(It doesn't matter if I write 10 or 2 in the substring, the first occurrence of the substring will return with the length value). I've tried with reference but it neither works…

What can be the root cause?

Thanks


Solution

  • Update:

    To get non formatted prices directly you can use:

    1) For the Order line item you can get the WC_Order_Item_Product Object with:

    $item_data     = $item['item']->get_data();
    $quantity      = $item_data['quantity'];
    $line_subtotal = $item_data['sub_total'];
    $line_total    = $item_data['total'];
    

    2) To get the related WC_Product object use:

    $product_data = $item['product']->get_data();    
    $product_price = $product_data['price'];
    

    You can use simply str_replace() removing euro symbol and spaces ('€' and ' ') this way:

    $price = str_replace( array(' ', '€'), array('', ''), floatval( $item['price'] ) );
    

    You will get a number (here 250) that you can use in your calculations