0

I'm trying to change the WooCommerce price dynamically on WooCommerce, already tried various solution posted here, but no one worked for my case.

Here's an example, I have an ajax function that calls the receive_order_ajax_request function, add the products into the cart, and after I call the update_vehicle_price to update the product's price. But all products remains with the same price. Can someone give me a help?

class WhollOrder {

    public function __construct() {
        add_action( 'wp_ajax_nopriv_receive_order_ajax_request', array( $this, 'receive_order_ajax_request' ) );

        add_action( 'wp_ajax_receive_order_ajax_request', array( $this, 'receive_order_ajax_request' ) );
    }


    public function receive_order_ajax_request() {
        global $woocommerce;

        $booking_details = $_POST['booking_details'];

        if ( isset( $booking_details ) && ! empty( $booking_details ) ) {
            foreach ( $booking_details['vehicles'] as $vehicle ) {
                $woocommerce->cart->add_to_cart( $vehicle['product_id'], (int) $vehicle['product_qty'] );
            }

    $this->update_vehicle_price( $booking_details['vehicles'] );
    } else {
    wp_send_json_error(
    array(
    'message' => 'Preencha todos os campos'
    )
        );
        }

        wp_die();
    }

    private function update_vehicle_price( $vehicles ) {
        global $woocommerce;

        foreach ( WC()->cart->get_cart() as $key => $cart_item ) {
            foreach ( $vehicles as $vehicle ) {
                if ( $vehicle['product_id'] == $cart_item['product_id'] ) {
                    WC()->cart->get_cart()[$key]['data']->set_price( 1000.00 );
                }
            }
        }

    }
}

new WhollOrder();

This is not a duplicate because the way I coded is not possible to use the others question's answers.

  • @LoicTheAztec This is not a duplicate because I'am trying to do a different thing as the other questions, just see the my code and compare to them, I'm not using hooks to change the price. – Cesar Henrique Damascena Jul 11 '18 at 20:05
  • Sorry but your code is just incomplete, so nobody can really get what you are doing wrong…Remember that *"Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error **and the shortest code necessary to reproduce it in the question itself.*** To change cart items prices using `set_price()` method can only be done in `woocommerce_before_calculate_totals`. – LoicTheAztec Jul 11 '18 at 20:38

1 Answers1

0

Yea dude, I've been here. The price is reloaded after you go to the checkout page.

You need to set it using this hook : woocommerce_checkout_create_order_line_item.

Change cart item prices in WooCommerce version 3.0

TurtleTread
  • 1,297
  • 2
  • 12
  • 23