3
votes

I have a custom pricing WP page with pricing table. There I get 3 parameters, namely, $product_id, $quantity, $total_price. I've created the products as normal WC products, gave each an initial price, description...etc, and obtained the IDs.

Then parameters are sent via Ajax to a PHP function. This function:

function my_ajax_functions() {
    check_ajax_referer( 'my_ajax_nonce', 'security' );
    if('checkout' == esc_attr($_POST['required_action'])) {
        $product = esc_attr($_POST['product_id']);
        $qty = esc_attr($_POST['quantity']);
        $price = ltrim(esc_attr($_POST['total_price']), '$');
            WC()->cart->empty_cart();
            WC()->cart->add_to_cart( $product, $qty);
            $cart = WC()->cart->get_cart_contents();
            foreach( $cart as $key => $value ) {
                $value['data']->price = $price/$qty; // Set the per unit price, so, it match when cart sub total is calculated
            }
            WC()->cart->set_cart_contents($cart->cart_contents);
            WC()->cart->maybe_set_cart_cookies();
            WC()->cart->calculate_totals();
    }
    die();
}

The problem I'm facing is although, product is added, quantity is added, the cart insists on showing, calculating according to the initial product price.

Example:

Let's say product A has an initial price $15... In the pricing page, customer ordered let's say 5 units, accordingly the price is $75. If he adds a 6th unit, het gets 50% discount (only on additional unit, the whole units), so, price for 6 units becomes $82.5. This what the page send via Ajax:

  • product_id = ID of product A (goes correctly)
  • quantity = 6 (goes ok)
  • total_price = $82.5 (here is the problem)

No matter what I do, the cart shows total = 6 x 15 = $90

What am I missing here??

Thanks.

1

1 Answers

0
votes

What about this?

function my_ajax_functions() {
    check_ajax_referer( 'my_ajax_nonce', 'security' );
    if('checkout' == esc_attr($_POST['required_action'])) {
        $product = esc_attr($_POST['product_id']);
        $qty = esc_attr($_POST['quantity']);
            $price = ltrim(esc_attr($_POST['total_price']), '$');
            WC()->cart->empty_cart();
            WC()->cart->add_to_cart( $product, $qty);
            $cart = WC()->cart->get_cart();
            foreach( $cart as $key => $value ) {
                $value['data']->set_price($price/$qty); // Set the per unit price, so, it match when cart sub total is calculated
            }
            WC()->cart->maybe_set_cart_cookies();
            WC()->cart->calculate_totals();
    }
    die();
}