15 November 2011

Redirect users to their main language first visit. I needed it only on the front page, but you can simply remove the if statement if you need the functionality on every page. The language detection is done by Smart IP. Which is a separate module.

I made a separate module for this. The code uses smart_ip module so i made it a requirement.
Source code viewer
  1. name = Smart IP redirect
  2. description = "Redirect users to right language on first visit, using Smart IP for country detection."
  3. core = 7.x
  4.  
  5. dependencies[] = smart_ip
Programming Language: YAML
The code with comments. Everything should be self explanatory.
Source code viewer
  1. <?php
  2. /**
  3.  * Implements hook_init().
  4.  */
  5. function HOOK_init() { // don't forget to rename the HOOK to your modules machine name
  6. if(
  7. // if country is detected
  8. !empty($_SESSION['smart_ip']['location']['country_code']) &&
  9. // if is front page
  10. drupal_is_front_page() &&
  11. // if user has not been already redirected
  12. !isset($_SESSION['smartip_redirect'])
  13. ) {
  14. // load some global variables, language contains information about current language, base_url is base url
  15. global $language, $base_url;
  16. // load all active languages
  17. $languages = language_list();
  18.  
  19. // if current language is not active language
  20. if(strtoupper($language->language) != $_SESSION['smart_ip']['location']['country_code'])
  21. {
  22. // does the visitors language exist in our Drupal
  23. if(array_key_exists(strtolower($_SESSION['smart_ip']['location']['country_code']), $languages))
  24. {
  25. // set session variable mekaia_smartip_redirect if the user will be redirected
  26. $_SESSION['smartip_redirect'] = TRUE;
  27. // redirect user to the designated language
  28. drupal_goto($base_url.'/'.strtolower($_SESSION['smart_ip']['location']['country_code']));
  29. }
  30. }
  31. }
  32. }
Programming Language: PHP