homepage Welcome to WebmasterWorld Guest from
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

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


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";

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

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)

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.


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