在WooCommerce中动态更改产品价格

时间:2018-07-09 03:28:25

标签: php ajax wordpress woocommerce hook-woocommerce

我正在尝试在WooCommerce上动态更改WooCommerce的价格,已经尝试过此处发布的各种解决方案,但是没有人适合我的情况。

这里有一个例子,我有一个ajax函数,该函数调用receive_order_ajax_request函数,将产品添加到购物车中,然后在调用update_vehicle_price以更新产品价格后。但是所有产品的价格都相同。有人可以帮我吗?

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();

这不是重复的,因为我的编码方式无法使用其他问题的答案。

1 个答案:

答案 0 :(得分:0)

老兄,我去过这里。转到结帐页面后,将重新加载价格。

您需要使用以下钩子进行设置: woocommerce_checkout_create_order_line_item

Change cart item prices in WooCommerce version 3.0