G
G
GetCode2020-10-23 17:55:19
WooCommerce
GetCode, 2020-10-23 17:55:19

How to pass second price via ajax to woocommerce cart?

It was necessary to implement the output of the second price per click
. Using ajax, I pass variables to functions.php (wordpress) and it seems that there are no problems with this.

Next, the handler code in functions.php where I already broke my head

add_action ('wp_ajax_add_custom_price', 'add_custom_price'); 
add_action ('wp_ajax_nopriv_add_custom_price', 'add_custom_price'); 
add_action ('woocommerce_before_calculate_totals', 'add_custom_price');

function add_custom_price( $cart_object ) { 
    $custom_price = $_REQUEST['regular'] > 0 ? $_REQUEST['regular'] : 0; //для проверки в $_REQUEST['regular'] передается 1
    
    $s = 1;
    $p = 2; 
    
    if($custom_price == 1){
        foreach ( $cart_object->cart_contents as $key => $value ) { 
            if($value['data']->get_id() == 994){
                $value['data']->set_price($s);
            }
        }
        $my_exit = 1;
    }else{
        foreach ( $cart_object->cart_contents as $key => $value ) { 
            if($value['data']->get_id() == 994){
                $value['data']->set_price($p);
            }
        }
        $my_exit = 2;
    }
    echo $my_exit;        
}

$my_exit and $custom_price return 1 but set_price gets 2
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question