PHP数组元素丢失:SESSION存储的自定义文章类型浏览记录消失问题
问题描述
我有一个名为accessories的自定义文章类型,当打开该类型的单篇文章时,会将对应文章ID存入array。我在单篇文章页执行var_dump($_SESSION['recently_viewed']);时,可以看到文章ID已成功存入数组,但返回上一级页面后,该ID就从数组中被移除了。
复现步骤
- 访问
/accessories页面,此时还未打开任何该类型的单篇文章,$_SESSION['recently_viewed']为空。 - 接着访问ID为643的文章
/accessories/post-1,单页上的var_dump($_SESSION['recently_viewed']);输出结果为array(1) { [0]=> int(643) },符合预期。 - 此时返回
/accessories页面,再次执行var_dump($_SESSION['recently_viewed']);,输出结果变为空数组array(0) { }。
现有实现代码
<?php session_start(); // array that contains ID $recently_viewed_array = array(); // store the array in a session variable $_SESSION['recently_viewed'] = $recently_viewed_array; // Check if the session variable exists if(!isset($_SESSION['recently_viewed'])){ // if it doesn't, create an empty array $_SESSION['recently_viewed'] = array(); } if ( is_singular ( 'accessories' ) ): global $post; $current_post_id = $post->ID; if ( !in_array ($current_post_id, $_SESSION['recently_viewed']) ): $_SESSION['recently_viewed'][] = $current_post_id; endif; endif; var_dump($_SESSION['recently_viewed']); ?>
问题原因与修复方案
你的代码在每次页面加载时,都会先执行$_SESSION['recently_viewed'] = $recently_viewed_array;强制将session变量覆盖为空数组,只有当前页面是accessories单篇文章时,才会触发后续的ID添加逻辑。当你返回列表页时,不会触发单页的ID添加逻辑,session变量直接被重置为空,自然看不到之前存储的ID。同时你后续写的isset判断完全没有作用,因为前面已经强制给session变量赋值,永远不会走到这个判断分支。
修复后代码
<?php session_start(); // 仅当session变量不存在时才初始化空数组,不要每次加载页面都覆盖原有值 if(!isset($_SESSION['recently_viewed'])){ $_SESSION['recently_viewed'] = array(); } if ( is_singular ( 'accessories' ) ): global $post; $current_post_id = $post->ID; if ( !in_array ($current_post_id, $_SESSION['recently_viewed']) ): $_SESSION['recently_viewed'][] = $current_post_id; endif; endif; var_dump($_SESSION['recently_viewed']); ?>
内容的提问来源于stack exchange,提问作者Freddy
相关产品推荐
相关产品推荐

