Habib Rehman Habib Rehman - 1 year ago 74
PHP Question

How do checkout actually works in woocommerce wordpress

I have updated price of products i wanted to add those prices in cart, i am using this simple piece of code

update_post_meta( $product->id, '_regular_price', $frame_price_added);
to update the price of product adding with my custom price.
And in this
i have done it like this:

$frame_price = $res['_number_field'][0];
$frame_price_added = $product->price+$frame_price;

is price coming from woocomerce product and
is coming from my newly added price. Now when i was wondering how do i associate this new price to cart because now when i added it it doesn't add my custom price in it even though i'm updating the regular price.

Another thing i tried was doing
update_post_meta( $product->id, '_price', $frame_price_added);
this and what it did was on every refresh of page it adds and stores the custom price to product, and it gets saved.

Any idea how do we add the price without getting in trouble ?

Edit: One thing more i searched the function being called on add to cart and i didn't find any there was a action hook being called on
which had
but it didn't had any function. its kind of messy to get beneath commerce working

Answer Source

You can use woocommerce_before_calculate_totals hook to customize your cart items prices.

You can define $framed_price variables as global in your function, this way.

This is the code:

// getting your additional price outside the function (making any conditional calculations) 
$framed_price = 20;

add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10, 2 );
function add_custom_total_price( $cart_object ) {
    global $woocommerce, $framed_price;

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

Or get your custom price inside the hooked function (optionally, depending on how you get your custom price):

add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10, 2 );
function add_custom_total_price( $cart_object ) {
    global $woocommerce;
    $framed_price = 20;

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

This code is tested and working.

Naturally this code goes on function.php file of your active child theme (or theme) or in any plugin file.

Reference: WooCommerce Cart - Dynamic Price variable pass into custom price hook

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download