Welcome to WebmasterWorld Guest from 54.145.208.64

Forum Moderators: rogerd & travelin cat

Message Too Old, No Replies

setting cookie in WP

need help to set cookie

   
4:13 am on Jan 25, 2014 (gmt 0)

5+ Year Member



Hello,

I have been able to redirect to my WP m.url.com site from the html desktop version using javascript. However, I cannot figure out how to get the cookie set so I don't keep getting redirected. Any help appreciated.

Desktop Javascript redirect:
<script type="text/javascript">
function getCookie(c_name) {
var c_start, c_end;
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start)
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

var mycookie = "mycookie";
var mobilename = getCookie(mycookie);

if ((mobilename != 'myvalue') && (screen.width <= 699)) {
window.location = "http://m.url.com";
}
</script>


>>> I have the set cookie function in the function file - at the bottom.

$mycookievalue = "myvalue";
function set_mobile_cookie() {
if (!isset($_COOKIE['mycookie'])) {
setcookie("mycookie", $mycookievalue, time()+604800, "/", ".url.com");
}}
add_action( 'init', 'set_mobile_cookie');
2:05 pm on Jan 25, 2014 (gmt 0)

WebmasterWorld Senior Member lorax is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



I'm not real good with Javascript but I think your set cookie function happens after the redirect function executes. In otherwords - set_mobile_cookie() never runs.
2:30 pm on Jan 25, 2014 (gmt 0)

WebmasterWorld Senior Member lorax is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



Ah. I think I see what's happening - guessing here. When you call add_action('init','set_mobile_cookie') the action you've chosen is 'init' - I'd suggest you look for a different one. Init is typically used to initialize plugins. Maybe take a look at wp_loaded instead.

[codex.wordpress.org...]

Another thought is to package the Javascript with the set cookie statements so that you know you're controlling the full decision tree in one block of code.