OpenCart Set language through URL

Although the built-in language selection in OpenCart close to perfect, If you need a language switcher extension for any text anywhere on the site, here are simple code to create links that direct users to the store in a specific language.

This code may use http referer as redirect URL, so it’s no redirect URL need.

Open file in catalog/controller/module/language.php

Add this code before line 4:

[php highlight=””]

if (isset($this->request->get[‘lang’])) {

$this->session->data[‘language’] = $this->request->get[‘lang’];

if (isset($_SERVER[‘HTTP_REFERER’]) && (strpos($_SERVER[‘HTTP_REFERER’], $this->config->get(‘config_url’)) !== false) ) {

$this->redirect($_SERVER[‘HTTP_REFERER’]);

} else {

$this->redirect($this->url->link(‘common/home’));

}

} else
[/php]

Example:

[php highlight=”1,2,3,4,6,8,10,12,14,16,18″]
<?php
class ControllerModuleLanguage extends Controller {
protected function index() {
if (isset($this->request->get[‘lang’])) {

$this->session->data[‘language’] = $this->request->get[‘lang’];

if (isset($_SERVER[‘HTTP_REFERER’]) && (strpos($_SERVER[‘HTTP_REFERER’], $this->config->get(‘config_url’)) !== false) ) {

$this->redirect($_SERVER[‘HTTP_REFERER’]);

} else {

$this->redirect($this->url->link(‘common/home’));

}

} elseif (isset($this->request->post[‘language_code’])) {
$this->session->data[‘language’] = $this->request->post[‘language_code’];

if (isset($this->request->post[‘redirect’])) {
$this->redirect($this->request->post[‘redirect’]);
} else {
$this->redirect($this->url->link(‘common/home’));
}
}
[/php]

Now you may test your language in URL. If you have English and Spanish on your site and you would use:
http://yourstore.com/?lang=en (for English) or
http://yourstore.com/?lang=es (for Spanish)

Last Updated On: 5th July 2013