php - WooCommerce use custom price when placing order


I have setup a local Wordpress environment with WooCommerce. The goal is a buy-one-get-one of equal or lesser value scenario.

I have the cart displaying a single item per line. I have isolated the cart products by 'key' not 'product_id' which is necessary for the equal or lesser portion of the requirements. I have created an array of necessary 'key' and am matching that against the cart contents by 'key'. If the keys match,'set_price('0.00');'

This works on the cart page and checkout page. It all works beautifully until I process the order (currently using COD option only). Then all of the prices reset to the regular price as it appears on the product page (the "regular price"). So the orders do not reflect the actual cost.

Below is the code I have:

function resetPrice( $cart_obj ) {

global $allFreeItems; //all items in cart (and relevant data) that need to be free

$comparison_ids = array(); //isolate keys for comparison

foreach ($allFreeItems as $key => $value) {
    $comparison_ids[] = $allFreeItems[$key][1]; //get unique key for each line item

foreach ( $cart_obj->get_cart() as $cart_item ) {
    // The corresponding product key of line item
    $product_key = $cart_item['key'];
    // Compare value of above to array of key's and change value
    if (in_array($product_key, $comparison_ids)) {
        $cart_item['data']->set_price( 0.00 );
//        else
//       {
//           $cart_item['data']->get_price();
//       }

add_action( 'woocommerce_after_checkout_form', 'resetPrice');
add_action( 'woocommerce_before_calculate_totals', 'resetPrice');

I thought perhaps I wasn't using the correct hook, but all examples point towoocommerce_before_calculate_totals. The only difference I see is the everyone keeps using['product_id'] rather than how I am doing it by[key] Is there something that happens when I click the "place order" button that I am not seeing? Anyone know a way around this?

People are also looking for solutions to the problem: php - Transfer input data from form to paypal payment and save if payment was successful


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.