0

I'm trying to add a custom price to the cart using the following function (in functions.php):

//Change cart item price
function add_custom_price_callback( $cart_object ) {

$custom_price = intval($_POST['p_m']);
$target_product_id = intval($_POST['s_o_v']);         

foreach ( $cart_object->cart_contents as $value ) {

    //Single product
    if ( $value['product_id'] == $target_product_id ) {
        $value['data']->price = $custom_price;
    }
    //For variation
    if ( $value['variation_id'] == $target_product_id ) {
        $value['data']->price = $custom_price;
    }

}    
die();    
}

add_action( 'wp_ajax_add_custom_price', 'add_custom_price_callback' ); add_action( 'wp_ajax_nopriv_add_custom_price', 'add_custom_price_callback' ); add_action( 'woocommerce_before_calculate_totals', 'add_custom_price_callback' ); If I use static values on the variables the function works but I need to set the variables dynamically with an Ajax call.

I have added Ajax in "functions.php" by using:

//jQuery / Ajax on site
function site_scripts() {
    //jQ
    wp_enqueue_script( 'ww_site_script', get_stylesheet_directory_uri() . '/js/ww_site_script.js', array( 'jquery' ), null, true );
    //Ajax
     wp_localize_script( 'ww_site_script', 'ajax_p',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}
add_action( 'wp_enqueue_scripts', 'site_scripts' );

And here is my Ajax call:

//Send ajax values    
$( '.single_add_to_cart_button' ).click(function() {
    console.log(s_o_v); 
    console.log(p_m);

    var data = {
        action: 'add_custom_price',
        p_m: p_m,
        s_o_v : s_o_v
    };

    $.post( ajax_p.ajax_url, data, function(response) {
        console.log( response );
    }, 'json');
    });

The "console.log(respons);" gets the values that are echoed in the function but the admin-ajax returns 0. How do I send the values to the "add_custom_price_callback" function?

1

Try to change your add_custom_price_callback() as follows. Untested but should work.

function add_custom_price_callback() {
    $custom_price = intval($_POST['p_m']);
    $target_product_id = intval($_POST['s_o_v']);         

    foreach ( WC()->cart->get_cart() as $key=>$value ) {

        //Single product
        if ( $value['product_id'] == $target_product_id ) {
             $value['data']->set_price($custom_price);
        }
        //For variation
        if ( $value['variation_id'] == $target_product_id ) {
             $value['data']->set_price($custom_price);
        }
   }
   //to check if is work or not       
   wp_send_json(array($value['data']->get_price($custom_price)));   
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.