Habib Rehman Habib Rehman - 1 year ago 120
PHP Question

Adding Custom price with woocomerce product price in Cart & Checkout

I have added a custom field in the woocommerce which has extra price of frames for pictures, now if picture price is 10$ and user selects a frame it will add up 5$ let say and total will be 15$.

Now if i have added another product and selected frame it should act like same.
The solution which is near to what i'm trying to do is:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10, 2 );
function add_custom_total_price( $cart_object ) {
global $woocommerce;
$framed_price = $_SESSION['frame_price'];

foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price += $framed_price;

Reference : WooCommerce - Adding a custom price to each product in cart

I'm storing the frame value in session and it gets updated every time user click on the frame i'm using ajax on that and till that everything is working fine. i'm getting values as well.

Here is a test live link, and it's working.

The only thing which lacks in this logic is it isn't taking each product to add extra value and leave it.

I also tried using this:

if ($_SESSION['product_price_before'] == $value['data']->price)
$value['data']->price += $_SESSION['framed_price'];

But obviously it won't work as it's terminating doing only entry but it left others.

Is there any way to do it without iteration over cart elements as if we do that we have to check each and compare each save each product, in short not efficient and not going to happen at all?

Another thing came in my mind was if is there any way to extract the sub total and add my extra values to them and populate a grand total;

Another point what if we update each products price, but that would be kind of same problem for products view as we have to store all product's old values and update new values then after checkout re-assign those old values to products again. (ahh that was rubbish thinking from me never mind, what if user adds and want to spend more time on site Yes, then Prices are already messed up for him/her )

is there any more appropriate way to do this?


Answer Source

I found an answer to this, that's solve the issue:

// Change the line total price
add_filter( 'woocommerce_get_discounted_price', 'calculate_discounted_price', 10, 2 );
// Display the line total price
add_filter( 'woocommerce_cart_item_subtotal', 'display_discounted_price', 10, 2 );

function calculate_discounted_price( $price, $values ) {
    // You have all your data on $values;
    $price += 10;
    return $price;

// wc_price => format the price with your own currency
function display_discounted_price( $values, $item ) {
    return wc_price( $item[ 'line_total' ] );

Reference: woocommerce, how can i add additional cost in cart product total price?