php - 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.
解决方案
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();
推荐阅读
- javascript - 如何使这些数组正常工作?
- javascript - 以小写形式返回函数名
- sql - 如何返回一个字段中的最小值,消除基于另一个字段的重复项?
- macos - 如何抑制通过访问 macOS 上的 AVAudioEngine 的 inputNode 生成的警告
- python - 即时从 python 中的 subprocess.run() 获取输出
- google-maps - 在 Google Maps Places Autocomplete API 上限制特定城市的搜索
- java - 如何修复“未连接适配器;跳过布局”
- python - 如何在 Python 中将一个数组中的多列堆叠在一起?
- active-directory - terraform 无法创建 AD VM,因为缺少公共 ip
- javascript - 从邮件列表中检索名字和第二名