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.
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.Try the following instead:
1) For your code in the php page:
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:
Code goes in function.php file of your active child theme (or active theme). Tested and works.