homepage Welcome to WebmasterWorld Guest from 23.22.173.58
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / WordPress
Forum Library, Charter, Moderators: lorax & rogerd

WordPress Forum

    
setting cookie in WP
need help to set cookie
weddingm

5+ Year Member



 
Msg#: 4640030 posted 4:13 am on Jan 25, 2014 (gmt 0)

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');

 

lorax

WebmasterWorld Administrator lorax us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 4640030 posted 2:05 pm on Jan 25, 2014 (gmt 0)

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.

lorax

WebmasterWorld Administrator lorax us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 4640030 posted 2:30 pm on Jan 25, 2014 (gmt 0)

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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / WordPress
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved