1

I have created a template page in WordPress. I want save the value in the session by opening the template page link, but I do not get that value after being redirected to product page. So what am I doing wrong?

I'm trying in the code below.

This is template file where i set session!

<?php
/**
* Template Name: HDFC Coupon
*/

$coupon_code = 'HDFC10EGMKKRYD';
$coupon = new WC_Coupon($coupon_code);
$product_ids = $coupon->get_product_ids();

$_SESSION['HDFC_COUPON_VALID'] = true;

if(count($product_ids) == 1){
    $url = get_permalink(reset($product_ids));
}else{
    $url = wc_get_cart_url();
}
wp_redirect($url);
exit();

This is function.php code where i want to get session value, but i got black array of session!

<?php
session_start();

add_filter('woocommerce_get_price', 'woocommerce_get_price_fun', 10, 2);
function woocommerce_get_price_fun($price, $product){

    // here it's blank when i print this : print_r($_SESSION)

    if(is_product() && isset($_SESSION['HDFC_COUPON_VALID']) && $_SESSION['HDFC_COUPON_VALID']){
        // sonthing which i want to do after session value get.
    }
    return $price;
}

it's working fine when i comment this line wp_redirect($url);, but when i use redirect then it not save data in session.

FluffyKitten
  • 13,824
  • 10
  • 39
  • 52
Bhavik Hirani
  • 1,996
  • 4
  • 28
  • 46

1 Answers1

0

WooCommerce has it's own session handler, which you can use by calling WC()->session. https://docs.woocommerce.com/wc-apidocs/class-WC_Session_Handler.html

It's possible that this is conflicting with session writes if you're using the $_SESSION superglobal, particularly if you're calling exit before the session has been written.

Instead, try using

WC()->session->set('HDFC_COUPON_VALID', true);

and

WC()->session->get('HDFC_COUPON_VALID');

followed by

WC()->session->save_data();

benJ
  • 2,442
  • 1
  • 18
  • 16
  • still not working, still i can't get session value in redirected page ! it working with same page but it not save for those browser ! – Bhavik Hirani Jul 08 '20 at 04:42
  • sorry, i missed your reply! Updated my answer - try adding `WC()->session->save_data();` before you redirect. – benJ Jul 16 '20 at 14:29