I am setting up a simple mobile/desktop redirect using the technique from this page. I am also setting a cookie on the mobile site so that if the user wants to link back to the desktop site, that cookie will be read and the redirect will not take place. I am dealing with WordPress sites and while the redirect does work, the cookie is not working properly. Here is what is happening:
- Mobile redirect does work
- Cookie is successfully set (confirmed with a test page outside WP)
- When the user clicks back to the desktop site, the cookie isn’t not being seen and the user gets dumped back to the mobile site again.
I tested my code using 2 external static pages, and everything works 100%. Just not when I use the same exact code in WordPress. Here is my code from the header.php files on each site:
Desktop site
<?php
include('Mobile_Detect.php');
$detect = new Mobile_Detect();
if ( $detect->isMobile() && isset($_COOKIE["mobile"]) ) {
$detect = "false";
}
else if ( $detect->isMobile() ) {
header("Location:http://m.example.com");
}
?>
Mobile site
<?php setcookie('mobile','m', time()+3600, '/','.example.com'); ?>
The PHP code is the first thing in the file, before any HTML and there is no errant whitespace before or after it. I’ve tested this code by echoing some text and the script is there and doing what it should. It’s just that one problem of the cookie not being seen and stopping the redirect to the mobile site like it should.
After many hours, I need some help please!
Problem solved!
The desktop site, running Drupal, was the problem. It’s a caching issue or something, because if I run cron, the whole detection scheme works perfectly. The second time around, it doesn’t. It only works one time right after running cron. I’m going to have to get our resident Drupal pro to figure it out.
Thanks for all the help, though!