Language redirect with PHP and WordPress

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?

Related posts

1 comment

  1. 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();
      }
    }
    

Comments are closed.