Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Paresh Thakor picture Paresh Thakor · Aug 6, 2018 · Viewed 8.2k times · Source

I am creating a membership site and totally created static pages for each Membership plans (have only 3 plans). However, I have added products for each plan and when I hit SELECT PLAN button I redirect to some custom form where I ask users range of info we are going to use to fulfil the plan (same as sneakertub.com).

I have written code into the PHP page which will handle SUBMIT action of the form. This PHP file, infopage.php, will process POST data I sent via POST call and stores these all data into WC session.

$customer_name = $_POST["customer_name"];
$customer_email = $_POST["customer_email"];
$customer_sex = $_POST["customer_sex"];
$customer_age = $_POST["customer_age"];
$product_id = $_POST["product_id"];

global $wp_session;
$data = array(
       'customer_name' => $customer_name,
       'customer_email'   => $customer_email,
       'customer_sex'  => $customer_sex,
       'customer_age'     => $customer_age);
$wp_session['custom_SESSION_child']=$data;

WC()->session->set('custom_data_child', $data);

//Add product to WooCommerce cart.
WC()->cart->add_to_cart( $product_id )

However, I don't think the above code works. As I don't find values into session with any of the above technique. I have used wp_session, WC()->session and $_SESSION but no approach is working.

I am trying to access these values into functions.php this way,

add_action( 'woocommerce_before_calculate_totals', 'twf_additional_price', 1, 3 );

function twf_additional_price( $cart_object ) {

    global $wpdb;

    global $wp_session;
    $session_data_2 =  $wp_session['custom_SESSION_child'];
    $session_data = WC()->session->get('custom_data_child');
    var_dump($session_data);
    var_dump($session_data2);

    foreach ( $cart_object->cart_contents as $key => $value ) {
        $extra_charge = 0;
        if(isset($value['twf_user_custom_datas'])){
            $extra_charge = 100;
        }

        $value['data']->set_price($value['data']->price + $extra_charge);
    }
}

For now ignore the for loop. Main thing is

var_dump($session_data);
        var_dump($session_data2);

both dumps only NULL.

My main goal is to add the all above fields into Woocommerce checkout and order pages.

Please let me know what is wrong here. I know I might be working on very bad approach but I want Plan selection to checkout process same as sneakertub.com. Please let me know if there is any tutorial on this or proper way to do this. I prefer doing this without plugins but I am ready to use plugins as well.

I appreciate your attention.

Answer

LoicTheAztec picture LoicTheAztec · Aug 6, 2018

Updated - Instead of using sessions, you should use the last available argument in WC_Cart add_to_cart() method, which will allow you to add any custom cart item data.

For cart item price change based on calculations, is better to make the new price calculation before and to set it in that custom cart item data.

Try the following instead:

1) For your code in the php page:

$custom_data = array(); // Initializing

// Set the posted data as cart item custom data
if( isset($_POST['customer_name']) && ! empty($_POST['customer_name']) )
    $custom_data['custom_data']['name']  = sanitize_text_field( $_POST['customer_name'] );
if( isset($_POST['customer_email']) && ! empty($_POST['customer_email']) )
    $custom_data['custom_data']['email'] = sanitize_text_field( $_POST['customer_email'] );
if( isset($_POST['customer_sex']) && ! empty($_POST['customer_sex']) )
    $custom_data['custom_data']['sex']   = sanitize_text_field( $_POST['customer_sex'] );
if( isset($_POST['customer_age']) && ! empty($_POST['customer_age']) )
    $custom_data['custom_data']['age']   = sanitize_text_field( $_POST['customer_age'] );

// Set the calculated item price as custom cart item data
if( isset($custom_data['custom_data']) && sizeof($custom_data['custom_data']) > 0 && $product_id > 0 ) {
    // Get an instance of the WC_Product object
    $product = wc_get_product( $product_id );
    // Save the new calculated price as custom cart item data
    $custom_data['custom_data']['new_price'] = $product->get_price() + 100;
}

// Add product to cart with the custom cart item data
WC()->cart->add_to_cart( $product_id, '1', '0', array(), $custom_data );

Code goes in function.php file of your active child theme (or active theme). Tested and works.


2) Your revisited function that will change the cart item price:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 30, 1 );
function custom_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if( isset($cart_item['custom_data']['new_price']) )
            $cart_item['data']->set_price( $cart_item['custom_data']['new_price'] );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

All other custom cart item data is available under the cart item key 'custom_data' as an indexed array… So you will be able to get that data easily from the cart object, to save it in the order.