2

I need to create a language redirect function for a WordPress multisite that I'm working on. This redirect would be dependent on the user's browser settings. I figured I could create a session in the header file so that when visiting the site, the site checks whether a session has already been set, then redirects accordingly. The code placed at the top of header.php -

$url = $_SERVER['REQUEST_URI'];
function redirect() {
  $language = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
  switch( $language[0] ) {
    case 'sv':
      header( 'Location: /sv/' );
      break;
    case 'no':
      header( 'Location: /no/' );
      break;
    case 'da':
      header( 'Location: /da/' );
      break;
  }
}
if ( strlen($url) < 4 ) {
  session_start();
  if ( !isset($_SESSION[ 'language' ]) && empty($_SESSION[ 'language' ]) ) {
    $_SESSION[ 'language' ] = true;
    redirect();
  }
}

If I skip Header location and just output the switch case I can see that the browser language is fetched, but there are no redirects. Am I on the right track here or should I take a complete different approach?

Staffan Estberg
  • 6,795
  • 16
  • 71
  • 107
  • [check this link](http://stackoverflow.com/questions/6038236/http-accept-language) – Noman Jun 18 '15 at 06:17
  • 1
    Try setting absolute path for the header, eg. http://example.com/sv/. Also, there is no need for `!isset` since you are using `empty`. – sitilge Jun 18 '15 at 06:19
  • Thanks. I tried setting an absolute path (also included www) and it works in Chrome but neither Firefox or Safari... I'm aware the browser language output is different, I've corrected that in my code. – Staffan Estberg Jun 18 '15 at 06:57

1 Answers1

0

Try the code . use you domain name instead of 'example.com' .

 $url = $_SERVER['REQUEST_URI'];
    function redirect() {
      $language = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
      switch( $language[0] ) {
        case 'sv':


         wp_redirect('example.com/sv/');
          exit();
          break;
        case 'no':

         wp_redirect('example.com/no/');
          exit();
          break;
        case 'da':
         wp_redirect('example.com/da/');
             exit();
          break;
      }
    }

if ( strlen($url) < 4 ) {
  session_start();
  if ( !isset($_SESSION[ 'language' ]) && empty($_SESSION[ 'language' ]) ) {
    $_SESSION[ 'language' ] = true;
    redirect();
  }
}
sarath
  • 698
  • 6
  • 20
  • Thanks but that did not work at all. The wp_safe_redirect just sent me to random pages (!) on the site. I'm curious, would there be any difference in using wp_safe_redirect or Header location? Is it something with WP's own routing system that might be causing this? – Staffan Estberg Jun 18 '15 at 06:56
  • random pages means? not redirecting to the specified page? – sarath Jun 18 '15 at 08:10