Wednesday, August 5, 2009

auto redirect by language for magento

http://blog.nrgup.net/2009/04/magento-browser-language-detection/

On our Magento E-Commerce site we try to support four languages (English, Spanish, French and Korean). I wanted to automatically direct the visitor to the correct language store view when they came to the site based on their browser language preferences. I wrote the following instructions for anyone else who may want to do something similar.

Introduction

This article assumes you have a store with multiple store views that represent different languages, that you have enabled store code in the urls (Admin Panel → System → Configuration → Web → Url Options → Add store code to Urls → Yes) and you want to redirect your visitors that go to the root store Url to the most appropriate language store view based on their browser locale setting.

For example, if a user types www.mystore.com and their browser is set to french locale they would be redirected to www.mystore.com/fr/. If there was no store view with a match to their browser language locale then the default store would be used as the fallback, e.g. www.mystore.com/en/.

  • Your web server must have mod_rewrite enabled.
  • Enable Url rewriting (Admin Panel → System → Configuration → Web → Url Options → Use Web Server Rewrites → Yes).
  • Enable store code in the urls (Admin Panel → System → Configuration → Web → Url Options → Add store code to Urls → Yes).

For each store view you must set the code to the 2-letter browser locale code you wish to match upon. For example, we’ll create two store views (english and spanish):

Create the default English store view:

  • Go to Manage Stores (Admin Panel → System → Manage Stores).
  • Create a new store view
  • Set the store and name to appropriate values (e.g. Default Store and English)
  • Set the code to the country code, in this case en. This is the value that will be matched to the browser locale settings.
  • Keep the sort order as zero (0) as this will be our default language.

Create the Spanish store view:

  • Create a new store view
  • Set the store and name to appropriate values (e.g. Default Store and Spanish)
  • Set the code to the country code, in this case es. This is the value that will be matched to the browser locale settings. For a list of valid 2 letter country codes see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes.
  • Set the sort order two one (1).

You may have any number of additional store views, simply repeat the process above using the appropriate country code.

Before continuing, test that the store view urls work by typing the address into your browser. For example,www.mystore.com/en/ and www.mystore.com/es/ should both work.

To enable the automatic redirect of a visitor when they visit the main store url (e.g. www.mystore.com) with a browser that is set to use spanish as their desired language we need to modify the index.php as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require_once 'app/Mage.php';

/* Determine correct language store based on browser */
function getStoreForLanguage()
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($accept), $found)) {
$langs[] = $found[1];
$quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
}
}
// Order the codes by quality
array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
// get list of stores and use the store code for the key
$stores = Mage::app()->getStores(false, true);
// iterate through languages found in the accept-language header
foreach ($langs as $lang) {
$lang = substr($lang,0,2);
if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
}
}
return Mage::app()->getStore();
}

/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {
header('Location: '.getStoreForLanguage()->getBaseUrl());
exit;
}

#Varien_Profiler::enable();

#Mage::setIsDeveloperMode(true);

#ini_set('display_errors', 1);

umask(0);
Mage::run();

There are two parts to the code we have added. The first is a method called getStoreForLanguage which does the following:

  • Parse the HTTP_ACCEPT_LANGUAGE header (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4) sent by the browser for a set of desired languages and the priority code for each.
  • Sort the priority codes so the most desired language is first.
  • Iterate through the store views to find a store view that has a 2 letter ISO 639-2 country code that matches the desired language.
  • Return the store view if found or the default store view if not.

The second part of the code runs for each request and checks to see if we are requesting the root url and if so calls the above method to determine where we should send the visitor. This assumes your web store is located at the root level, if you installed Magento into a directory such as /magento (e.g. www.mystore.com/magento) you should change this line to be /magento instead.

Testing the detection

There are two ways you can test to see if the changes you have made work.

1 comment:

  1. Very nice piece of work. Just a question. I'm running my store with different domains for different store views (languages)

    So I have www.domain.com www.domain.de www.domain.fr etc.

    I guess your solution will not work for me?

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...
Web Design & Marketing - Click and get an instant quote on your project