Automatic detection of Opencart language (Without using the Module)

  • Automatic detection of Opencart language (Without using the Module)

If you need to automatically detect the user's language on Opencart, then there are two solutions:

1. Language definitions by IP (country or region)
2. Language definitions by browser language

We will use the second method , as we consider it more accurate.

Each browser sends a string with the ISO codes of the languages used and their priorities. In this example, we will take the language with the highest usage priority.

An example of code that will help you automatically detect the browser language and switch the site language to Opencart:

 if (! isset ( $this -> session -> data [ 'language_change' ])) {    
$this -> session -> data [ 'language_change' ] = '0' ; } if ( $this -> session -> data [ 'language_change' ]== '0' ) {
    $lang = substr ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], 0 , 2 );
    $this -> session -> data [ 'language_change' ]= '1' ; if ( $lang == 'ru' || $lang == 'uk' || $lang == 'be' || $lang == 'ky' || $lang == 'am' || $lang == 'ab' ){ 
        $_SESSION [ 'language' ] = 'ru' ;
        $this -> session -> data [ 'language' ]= 'ru' ;
        $this -> session -> data [ 'language_code' ]= 'en' ; } else { 
        $_SESSION [ 'language' ] = 'en' ; 
        $this -> session -> data [ 'language' ]= 'en' ;
        $this -> session -> data [ 'language_code' ]= 'en' ; }
    $this -> response -> redirect ( $_SERVER [ 'REQUEST_URI' ]); }

This code needs to be inserted into the controller, for example in /catalog/controller/common/header.php anywhere in the index() function.