doulu6234 2018-07-09 03:28
浏览 77

在WooCommerce中动态更改产品价格

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.

  • 写回答

1条回答 默认 最新

  • douzhannao5357 2018-07-09 21:11
    关注

    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

    评论

报告相同问题?