Set tracking cookie from link using URL query, redirect to selected link on return visit

拥有回忆 提交于 2020-06-01 07:39:34

问题


I have page with 4 links, when someone clicks on one of the links I want to set a cookie to store the selected link, then when they return to the site, the cookie redirects them to the link they previously selected. Since I only want the 4 links to set a cookie I'm using a query string (?sel=p1) in the link and checking for that to set the cookie.

function set_pref_cookie(){

    if (isset($_GET['sel'])) {
        $root = $_GET['sel'];

        if ($root = 'p1'){
            $cookie_var = '/page1/';
        } else if ($root = 'p2'){
            $cookie_var = '/page2/';
        } else if ($root = 'p3'){
            $cookie_var = '/page3/';
        } else if ($root = 'p4'){
            $cookie_var = '/page4/';
        }

    } else {
      $root = '';
    }

    if ($root !=''){
        setcookie('pref_sel',$_COOKIE['sel'] = $cookie_var, time()+60*60*24*5, "/");
    }

    if (isset($_COOKIE['pref_sel']) && $_COOKIE['pref_sel'] != ''){
        header('Location:' .  $_COOKIE['pref_sel']);
        exit;
    }
}

add_action('init','set_pref_cookie');

The issue is, all 4 links set the same value in the cookie /page1/ , and, on return to the site, I'm getting a redirect loop.

I've also tried checking for an empty cookie

if (isset($_COOKIE['pref_sel']) && !empty($_COOKIE['pref_sel']) ){

but same result.

来源:https://stackoverflow.com/questions/62026729/set-tracking-cookie-from-link-using-url-query-redirect-to-selected-link-on-retu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!