Pass WooCommerce session variables

I’ve been trying for 3 days now, but I just can’t get it to work.

My WooCommerce products have custom input fields, for the sake of this question let’s say 1 inputfield, called ‘test’.

Now, my code is as follows for saving the input:

function save_products_fields( $cart_item_key, $product_id = null, $quantity= null, $variation_id= null, $variation= null, $test_val = null ) {
    global $test_val;
    $test_val = $_POST['test'];

    if( isset($test_val) ) {
        WC()->session->set( $cart_item_key.'_test_value', $test_val );
    } else {
        WC()->session->__unset( $cart_item_key.'_test_value' );
add_action( 'woocommerce_add_to_cart', 'save_products_fields', 1, 5 );

I mean, this should work.

Next, I want to do some calculations before adding it to the cart:

function calculate_cart_total( $cart_object ) {

    $test_val = $_POST['test'];

    foreach ( $cart_object->cart_contents as $key => $value ) {       
        if( WC()->session->__isset( $key.'_test_value' ) ) {
            $quantity = intval( $value['quantity'] );
            $orgPrice = intval( $value['data']->price );
            $value['data']->price = ( ( $orgPrice + $test_val ) * $quantity );
add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 1 );

So, when – for example – the input contains 10, the product price should increase by 10.

Somehow, in my save_products_fields function, I can conditional check if the value exists and so on. The $_POST works.

But I can’t use the $_POST or even global $test_value in my calculate_cart_total function. I also tried WC_Session::get('_test_value') and WC_Session::__get('_test_value') but this isn’t working either.

I know the rest works, because if I do $test_val = 10 the price indeed changes.

Why is $_POST not working?

Source: wordpress

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.