【问题标题】:Set cookie if not exist, Update/override if exists in PHP如果不存在则设置 cookie,如果在 PHP 中存在则更新/覆盖
【发布时间】:2019-01-24 17:46:38
【问题描述】:

我想存储访问者访问过的博客的数据。我会在最近访问的博客部分展示给他们看。 对于这个功能,我当然必须使用 Cookie。

所以我想检查 cookie 是否存在, 如果不存在,则应使用当前页面 ID 的值创建一个新 cookie。 如果存在,则应将我当前页面的 ID 添加到 cookie 中的字符串中。

下面是我的代码,它不起作用。 PS:我在评论中提到了一些事情

global $wp_query; //Its global variable in Wordpress

if(!isset($_COOKIE['recent_posts'])) {

    $cookie_value = $wp_query->post->ID; //this returns current page's ID

    setcookie('recent_posts', $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

    $_COOKIE['recent_posts'] = $cookie_value;

    echo $_COOKIE['recent_posts'];
} 
else {

    $previous_cookie = $_COOKIE['recent_posts'];

    $current_cookie = $previous_cookie.','.$wp_query->post->ID;

    setcookie('recent_posts', $current_cookie, time() + (86400 * 30), "/"); // 86400 = 1 day
}

【问题讨论】:

标签: php wordpress cookies


【解决方案1】:

请在 get_header 之前使用 cookie 或在 init action wordpress 中使用它。

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2015-03-31
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多