Conditional Redirect

I'm looking to do a redirect based on browser, but only for a specific page (or 2). I'd like to send the user to an alternative page if the browser is IE7 or less. The alt page will have completely different setup and everything to work for their old crap.

I can't find a plugin. I'm looking at doing a php inject plugin to make this page specific.

Any advice?

Topic browser-compatibility redirect Wordpress

Category Web


The phpbrowscap class looks perfect for what you're trying to do. First, you'd need to download the source from github upload the Browscap.php file to the server, then use the following php to check what version of IE is being used and redirect to a different URL based on version:

// Loads the class
require 'Browscap.php';

// The Browscap class is in the phpbrowscap namespace, so import it
use phpbrowscap\Browscap;

// Create a new Browscap object (loads or creates the cache)
$bc = new Browscap('cache');

// Get information about the current browser's user agent
$current_browser = $bc->getBrowser();

//only do something if browser is IE
if($current_browser->Browser == "IE") {

  // print the resulting stdClass object, remove this in final code!
  echo '<pre>'; // some formatting issues ;)
  print_r($current_browser);
  echo '</pre>';

  switch($current_browser->MajorVer){
    case ("11"):
      echo "Browser is IE 11!";
      break;
    case("10"):
      echo "Browser is IE 10!";
      break;
    case("9"):
      echo "Browser is IE 9!";
      break;
    case("8"):
      echo "Browser is IE 8!";
      $url = home_url() . "/ie8page";
      wp_redirect($url);
      exit(); // this is required after wp_redirect per the codex!
      break;
    case("7"):
      echo "Browser is IE 7!";
      //$url = home_url() . "/ie7page";
      //wp_redirect($url);
      //exit(); // this is required after wp_redirect per the codex!
      break;
  }
}

If you want to detect only IE specific browsers, then following code help you. You need to replace the comments with the redirection code

function browser_detection_redirect(){
preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);

if (count($matches)>1){
  //Then we're using IE
  $version = $matches[1];

  switch(true){
    case ($version<=8):
      //IE 8 or under!
      break;

    case ($version==9):
      //IE9!
      break;

    default:
      //You get the idea
  }
}
}

You have to call the function on WordPress init hook to redirect:

add_action('init', 'browser_detection_redirect');

To add this code on the specific page you need to use the is_page WordPress function.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.