No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
MVC-L: controllers, models, templates

OpenCart language files: how to translate a module in 3.0 and 4.1

Where module language files live in OpenCart 3.0 and 4.1, how the Language class loads them, why you see keys instead of text, and how to add Ukrainian correctly.

11 min read OC 3.0 OC 4.1

OpenCart language files are plain PHP files containing an $_ array, where each key such as heading_title or error_name holds a ready-to-use interface string. The controllerCode that receives a request and prepares data. More in the glossary → loads them through $this->load->language(), and the template displays strings by their keys. To translate a module, you put a file with the same keys in the directory of the target language (for example, uk-ua) at the correct path. The paths and behavior of the Language class differ between OpenCart 3.0 and 4.1, and these differences cause most of the errors.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What is a language file and what does it look like inside?

A language fileA PHP file with interface texts, separate for each language. More in the glossary → is the "L" in the MVC-L scheme. It outputs nothing and contains no logic; it only fills the $_ array. For how it interacts with the controller, model, and template, see the overview MVC-L in OpenCart. Here is a fragment of a standard product card language file:

catalog/language/en-gb/product/product.php · OpenCart 3.0.5.1 · lines 14–17

$_['text_minimum']             = 'This product has a minimum quantity of %s';
$_['text_reviews']             = '%s reviews';
$_['text_write']               = 'Write a review';
$_['text_login']               = 'Please <a href="%s">login</a> or <a href="%s">register</a> to review';

This fragment shows three features of the format:

  • Placeholders %s and %d. The string is intended for sprintf(), so the controller substitutes the values. The translator must keep the number and order of the placeholders.
  • HTML in strings is allowed. In the standard OpenCart configuration, Twig auto-escaping is disabled, so markup from the language file is output as is. The downside: user data must not be inserted into such strings without escaping.
  • Key prefixes follow an unofficial but stable convention: heading_title for headings, text_* for regular text, entry_* for form field labels, help_* for hints, tab_* for tabs, column_* for table columns, button_* for buttons, error_* for error messages.

Shared strings such as button_save, button_cancel, or text_enabled are located in the main language file (en-gb.php, uk-ua.php, and so on, in the root of the language directory). The core loads it at the start of the request, so these keys do not need to be duplicated in the module. Override them only when you need different wording.

Where do module language files live in OpenCart 3.0 and 4.1?

A language file always mirrors the controller route: the admin and the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → have separate files, and each language has its own subdirectory. The general directory map is described in the article on OpenCart file structure. Here we cover only what matters for translating a module with the conditional code my_notice.

ItemOpenCart 3.0OpenCart 4.1
Admin languageadmin/language/uk-ua/extension/module/my_notice.phpextension/my_notice/admin/language/uk-ua/module/my_notice.php
Storefront languagecatalog/language/uk-ua/extension/module/my_notice.phpextension/my_notice/catalog/language/uk-ua/module/my_notice.php
Call in the controllerload->language('extension/module/my_notice')load->language('extension/my_notice/module/my_notice')
Fallback to en-gbYes, built into Language::load()No, only the current language file is read
Key groupingSub-object via the $key argumentPrefix via the $prefix argument

OpenCart 3.0: the module places its files in the shared core directories, so the language file sits next to the standard files of other extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary →.

OpenCart 4.1: the extension lives in its own extension/<код>/ folder. The language file is looked up inside it, and the extension/<код> segment in the route is converted by the core into the path to this folder. The details of this process are covered in the next section. The principle of converting a route into a path to the controller is explained in the article on route= routing in 3.0 and 4.1.

How the Language class loads files: the difference between 3.0 and 4.1

The $this->load->language() call in the controller hands the work to the language object from the registry (see the articles on Loader and Registry for more). It behaves differently in the two branches.

OpenCart 3.0: en-gb first, then the current language

system/library/language.php · OpenCart 3.0.5.1 · lines 60–84

	public function load($filename, $key = '') {
		if (!$key) {
			$_ = array();
	
			$file = DIR_LANGUAGE . $this->default . '/' . $filename . '.php';
	
			if (is_file($file)) {
				require($file);
			}
	
			$file = DIR_LANGUAGE . $this->directory . '/' . $filename . '.php';
			
			if (is_file($file)) {
				require($file);
			} 
	
			$this->data = array_merge($this->data, $_);
		} else {
			// Put the language into a sub key
			$this->data[$key] = new Language($this->directory);
			$this->data[$key]->load($filename);
		}
		
		return $this->data;
	}

Both files write data into the same $_ array, so the Ukrainian strings override the English ones, and keys missing from the translation remain in English. This is convenient during partial translation, but it hides missing keys: a module that is "half English" is not considered an error.

OpenCart 4.1: one language, cache, and extension paths

system/library/language.php · OpenCart 4.1.0.4 · lines 135–164

		if (!isset($this->cache[$code][$filename])) {
			$_ = [];

			// Load selected language file to overwrite the default language keys
			$file = $this->directory . $code . '/' . $filename . '.php';

			$namespace = '';

			$parts = explode('/', $filename);

			foreach ($parts as $part) {
				if (!$namespace) {
					$namespace .= $part;
				} else {
					$namespace .= '/' . $part;
				}

				if (isset($this->path[$namespace])) {
					$file = $this->path[$namespace] . $code . substr($filename, strlen($namespace)) . '.php';
				}
			}

			if (is_file($file)) {
				require($file);
			}

			$this->cache[$code][$filename] = $_;
		} else {
			$_ = $this->cache[$code][$filename];
		}

Here there is no second require for en-gb: only the $code language file is read. Extension paths are registered via addPath(). For the extension/my_notice/module/my_notice route, the extension/my_notice namespace applies, and the file is searched in its language/ directory, then in the language code subdirectory with the /module/my_notice.php suffix. If the Ukrainian file is missing, get() returns the key itself ($this->data[$key] ?? $key), and text_title appears on the page instead of the text. The same happens in 3.0 when the key is missing from all files.

flowchart TD
    A["Controller: load->language(route)"] --> B{"Version?"}
    B -->|"3.0"| C["require en-gb/file.php"]
    C --> D["require uk-ua/file.php on top"]
    B -->|"4.1"| E{"In cache?"}
    E -->|"Yes"| G["Take array from cache"]
    E -->|"No"| F["Path via addPath, require uk-ua only"]
    F --> G
    D --> H["array_merge into data"]
    G --> H
    H --> I["get(key): string or the key itself"]

How to load the language in the controller and output strings in Twig?

Let's create a minimal storefront module with two strings. First, the language file for OpenCart 4.1:

<?php
// extension/my_notice/catalog/language/uk-ua/module/my_notice.php
// Heading
$_['heading_title'] = 'Важливе оголошення';

// Text
$_['text_delivery'] = 'Відправляємо Новою Поштою протягом %d робочих днів';
$_['text_link']     = 'Умови доставки — <a href="%s">детальніше</a>';

The controller for OpenCart 4.1:

<?php
namespace Opencart\Catalog\Controller\Extension\MyNotice\Module;
class MyNotice extends \Opencart\System\Engine\Controller {
	public function index(): string {
		$this->load->language('extension/my_notice/module/my_notice');

		$data['text_delivery'] = sprintf($this->language->get('text_delivery'), 2);
		$data['text_link'] = sprintf($this->language->get('text_link'), $this->url->link('information/information', 'language=' . $this->config->get('config_language') . '&information_id=6'));

		return $this->load->view('extension/my_notice/module/my_notice', $data);
	}
}

OpenCart 3.0: the class is called ControllerExtensionModuleMyNotice, the language is loaded as $this->load->language('extension/module/my_notice'), and the template as extension/module/my_notice. The logic is the same.

Strings without placeholders do not need to be passed from the $data. In both versions, the standard language event before rendering (view/*/before) adds all loaded strings to the template variables, unless the controller passed a variable with that name itself. So in the template you can write {{ heading_title }} directly:

<div class="my-notice">
  <h3>{{ heading_title }}</h3>
  <p>{{ text_delivery }}</p>
  <p>{{ text_link }}</p>
</div>

Strings with %s are better formatted in the controller rather than with a filter in the template. This keeps the logic in one place, and the Twig template does not depend on the argument order. For more on passing $data, see the article on OpenCart controllers, and for variables and filters, see Twig in 3.0 and 4.1.

How to load multiple files without key conflicts and output text in the client's language?

The load() method merges arrays via array_merge. The second file overwrites same-named keys of the first, most often heading_title and text_success. If one controller needs strings from two files, group the second file.

OpenCart 3.0: the second argument of $key creates a nested Language object. After $this->load->language('extension/module/my_notice', 'notice'), the string is available as $this->language->get('notice')->get('heading_title'), and the main array is unchanged.

OpenCart 4.1: the second argument of $prefix renames the keys to notice_heading_title, notice_text_delivery, and so on, and $this->language->all('notice') returns them without the prefix. This is how the core collects strings when one controller renders several blocks.

Text in a language other than the current request's

A typical situation: the administrator works in the Ukrainian admin, but a status-change email must be sent in English because the order was placed through the English version of the store.

  • OpenCart 4.1: the third argument of load($filename, $prefix, $code) allows loading a file of another language. The file cache is separated by language code, but strings are merged into the shared data array, so for another language you must always specify $prefix, otherwise they will overwrite the interface strings.
  • OpenCart 3.0: there is no such argument. Create a separate instance of new Language($directory) with the order's language directory, load the main language file and the needed email file into it, and take the strings from that object. The global $this->language remains unchanged.

How to add Ukrainian to a third-party module without breaking the site?

Translation is most often needed for a ready-made module that has only en-gb. The procedure:

  1. Make sure the Ukrainian language is installed and enabled: System → Localisation → Languages. Check its code and directory, for example uk-ua.
  2. Find all module files in en-gb separately for the admin and the storefront. In 4.1 they are in extension/<код>/admin/language/en-gb/ and extension/<код>/catalog/language/en-gb/.
  3. Copy them into the sibling uk-ua directory, preserving the nesting and file names.
  4. Translate only the values. Do not change keys, %s/%d placeholders, or HTML attributes.
  5. Save the files in UTF-8 without BOM and check the syntax with the php -l command.
  6. Open the module's pages in Ukrainian and search them for "bare" keys such as entry_status. In 4.1, missing strings show up this way, because there is no fallback to en-gb.
Language list: check the language code, which is also the directory name for the language files
Language list: check the language code, which is also the directory name for the language files · OpenCart 4.1.0.4
find extension/my_notice -path '*uk-ua*' -name '*.php' -exec php -l {} \;

Two pitfalls that break the page

Apostrophe. Strings in language files are enclosed in single quotes, and in Ukrainian the apostrophe appears constantly: "зв'язок", "ім'я", "обов'язкове". Writing 'Ім'я' ends the string early, and PHP throws a parse error, resulting in a white page or a 500. Wrap such a string in double quotes (this is done, for example, for error_product in the standard product.php of version 3.0An older branch with a large number of ready-made modules; many stores still run on it. More in the glossary →), escape \', or use the typographic apostrophe ’. Inside double quotes, watch for the $ character, because PHP will try to substitute a variable.

BOM. A file saved as "UTF-8 with BOM" outputs three invisible bytes before the headers. Consequences: the "headers already sent" error, broken JSON in AJAX responses (see the article on AJAX and JSON responses in controllers for details), and layout shifts on the storefront.

When is the "Language Editor" in the admin enough?

If you need to change a few phrases on the storefront, for example "Buy" to "Order" or the availability text, you don't necessarily need to edit files. In Design → Language Editor (Design → Language Editor), you choose the store, language, language file route, and key, and set a new value. Overrides are stored in the database, in the translation table, and are applied on top of the files. Therefore they survive module or theme updates.

Language Editor: overriding a single key for the selected language and store
Language Editor: overriding a single key for the selected language and store · OpenCart 4.1.0.4

Understand the limitations in advance:

A working rule: the module developer always ships complete language files for every language, and the store owner makes point corrections to the wording through the editor. It's also worth remembering that language files only cover the interface. Product names, category names, and SEO URLs for each language are stored in the database. Language prefixes in URLs and hreflang are covered in a separate article on setting up multilingual support in OpenCart.

Summary

  • A language file is a PHP array $_ with keys following the convention heading_title, text_*, entry_*, error_*. Its path repeats the controller route separately for admin and catalog.
  • OpenCart 3.0: module files are in admin|catalog/language/<мова>/extension/module/, and Language::load() first reads en-gb, then the current language.
  • OpenCart 4.1: files are in extension/<код>/admin|catalog/language/<мова>/, only the current language file is read, and a missing key is visible on the page as is.
  • $key sub-object in 3.0 or $prefix with all($prefix) in 4.1. Another language is loaded with the $code argument in 4.1 or a separate Language instance in 3.0.
  • Before release, check apostrophes, UTF-8 encoding without BOM, and the result of php -l.

Next, it's worth understanding how strings get into the template and how the controller assembles the page. All articles in this section are collected on the page MVC-L: controllers, models, templates.

FAQ

Can I store module translations in the database instead of files?
Yes, but then you have to write the loading and caching yourself. OpenCart's standard mechanism is built around files, and the database is used only for point overrides through the “Language Editor”.
Why did my Ukrainian translation disappear after a module update?
The update archive most often contains only en-gb or overwrites your files. Keep your translation in version control and after every update compare the key sets of en-gb and uk-ua.
Do I need to clear the cache after changing a language file?
OpenCart's file cache does not store language files. In 4.1 the Language class cache lives only within a single request, so changes show up immediately. If OPcache is enabled on the server with file modification time checks disabled, restart PHP-FPM.
How do I quickly find keys that are missing from a translation?
Compare the key arrays of en-gb and uk-ua with a small CLI script that includes both files and outputs array_diff_key. This is more reliable than searching for “bare” keys on pages by hand.
Can I use one language file for both admin and storefront?
No, admin and catalog are separate applications with different language directories, and each looks for files only in its own. Shared strings have to be duplicated in both files.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.