首页 > 解决方案 > Session not save after redirect in WordPress

问题描述

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.

标签: phpwordpresssessionwoocommerce

解决方案


WooCommerce 有自己的会话处理程序,您可以通过调用WC()->session. https://docs.woocommerce.com/wc-apidocs/class-WC_Session_Handler.html

如果您使用超全局,这可能与会话写入冲突$_SESSION,特别是如果您在exit会话写入之前调用。

相反,请尝试使用

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

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

其次是

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


推荐阅读