Change product price with AJAX, Woocommerce WordPress

I’m working with a custom product where customers can type their custom text that will be added to cart.
Depending on the size of the text, a different price will be set, the logic is done and I can see the new price in the product object.

It seems that I can change the product object with the new price but I get status 500 back from admin-ajax.php when I do $woocommerce->setup_product_data($product_id).

Read More

I have found several topics but none of them seems to work in my case.
I’m not able to update the cart with the new price.

Here is my ajax function in functions.php:

// Adjust new price
function applyNewPrice() {
    global $woocommerce;

    // From JS
    $product_id = (int) $_POST['id']; 
    // From JS
    $price = (float) $_POST['price'];
    $product_data = get_post($product_id);
    // Code returning status 500 here...
    $product = $woocommerce->setup_product_data($product_data); 
    $product->set_price($price);

    update_post_meta($product_id,'_price',$price);
    update_post_meta($product_id,'_regular_price',$price);

    $woocommerce->clear_product_transients( $product_id );

}

add_action('wp_ajax_applyNewPrice', 'applyNewPrice');
add_action('wp_ajax_nopriv_applyNewPrice', 'applyNewPrice');

Related posts

1 comment

  1. The function you are trying to call does not exist. This is the function you need.

    $product = wc_setup_product_data( $product_id );
    

    No sure where you are coming up with those functions. I could not find this function either?

    $woocommerce->clear_product_transients( $product_id );
    

Comments are closed.