Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Translations Hooks

WordPress Filters relating to detecting & translating words

Weglot plugin will detect all the words in your HTML. To do this, it will parse the DOM in PHP and detect the inner text of HTML nodes but also some attributes we have defined, like the "placeholder" attribute in a <input> node or the "alt" attribute of an img node.

This usually ensure all the text in your page is detected and get translated. However, in some case, your text can be located in other location in your HTML. Like it could be in a JavaScript variable like this

<script>
var myAwesomeVar = 'This is a text I would like to translate';
</script>

In that case, your text will not be detected and not be translated.

This is where you will use filters to extend the definitions of the Weglot Parser and instruct it to detect other text.

Extend what gets detected

weglot_get_dom_checkers

This filter extend the list of HTML nodes and attribute that are being translated.

Argument
Type
Description

$dom_checkers

array

Names of used DomChecker (extends Weglot\Parser\Check\Dom\AbstractDomChecker)

Use case

It can happen in your HTML that you use data-attributes that are not translated by default. Example with data-slide-title

<div data-slide-title="Title slide">
    New project !
</div>

With the weglot_get_dom_checkers filter, you will extend the list of "Dom checkers" by adding a class in the list like on the following example.

Removing a checker

Some attributes Weglot detects by default may not make sense on your site. A common case is a data-value holding a slug that your JavaScript compares against: translating it silently breaks the filtering, while the visible label still has to be translated.

The same filter removes checkers — return the array without the classes you do not want.

Pass as many classes as you need:

Checkers you can remove

$dom_checkers holds the checkers added by the WordPress plugin. These are the ones you can remove:

Class
Tag
Attribute translated

\WeglotWP\Domcheckers\Button_Data_Value

button

data-value

\WeglotWP\Domcheckers\Button_Value

button

value

\WeglotWP\Domcheckers\Input_Reset

input[type="reset"]

value

\WeglotWP\Domcheckers\Link_Data_Href

a

data-href

\WeglotWP\Domcheckers\Video_Source

video source, video

src

\WeglotWP\Domcheckers\Meta_Facebook_Image

meta og:image

content

\WeglotWP\Domcheckers\Meta_Twitter_Image

meta twitter:image

content

\WeglotWP\Domcheckers\Meta_Twitter

meta twitter:card, site, creator

content

The parser library loads its own checkers (Text, ImageAlt, Placeholder, LinkHref, LinkTitle, Button, …) before this filter runs, so they are not part of $dom_checkers and cannot be removed this way.

In particular, the inner text of your elements is detected by the library's Text checker. Removing a checker only ever stops an attribute from being translated — the visible text of the element keeps being translated.

weglot_get_regex_checkers

This filter is a bit more tricky to understand but also very powerful. It allows you to give a Regex to the parser in order for it to detect the text you want in your DOM.

Argument
Type
Description

$regex_checkers

array

Used RegexChecker

$regex_checkers is an array that contains the RegexChecker objects, which determine what elements to treat as well as the type of data it is (TEXT, HTML or JSON).

The RegexChecker constructor settings are as follows:

  • $regex: Regex that target the element you want to be parsed

  • $type: String variable that determines the type of the targeted element ('TEXT', 'HTML' or 'JSON')

  • $var_number: Denotes the number of variable targeted by the regex that you want to parse

  • $keys: If the element being treated is a 'JSON' element, this variable allows you to specify keys to translate

  • $callback: Function callback applied to intercepted content

  • $revert_callback: Function callback applied to returned content

Use case

Below are several examples of content that will not be translated by default by Weglot, but that you can translate using this filter

In order for the content in this example to be interpreted, and then translated, we will use the weglot_get_regex_checkers filter as followed.

weglot_words_translate

Use this filter to target a specific word literally in your source code.

Argument
Type
Description

$words

array

Array of string

You can add words that are present in your HTML page but not translated. It's useful when a word is not being translated by Weglot because it's inside a JavaScript for example and you can't really use other filters.

Use case

This filter will tell Weglot to look literally for words in your source code, then translate it and literally replace these words in your source code. Be very careful to not enter keywords as "head" "body" for example as it could break your page.

weglot_preserve_words_enabled / weglot_preserve_words_list

The mirror image of weglot_words_translate: use these two filters to keep specific words untranslated, wherever they appear on the page (brand names, product references, etc.).

  • weglot_preserve_words_enabled — return true to turn the feature on (default false).

  • weglot_preserve_words_list — return the array of literal words to preserve (default empty). It also receives the page content as a second argument if you need to build the list dynamically.

weglot_get_parser_ignored_nodes

Change the list of inline tags (strong, em, abbr…) the parser keeps inside the surrounding sentence instead of handling them as separate nodes: their text is sent for translation together with the sentence, as one string. The filter receives the default list of tag names provided by the parser and must return the modified list.

This list is only used when the project runs translation engine 2. Engine 3 (the default) keeps inline tags inside the sentence by itself, and engine 1 (legacy API keys) does not use the list.

Whitelist & exclude blocks

By default, everything on a page is translated except the blocks you exclude. These two filters give you both sides of that control from your code.

weglot_parser_whitelist

This filter flips the page into opt-in mode. By default Weglot translates the whole page; when the array returned by this filter is not empty, Weglot adds a wg-mode-whitelist attribute to the <body> tag and translates only the blocks matching the listed CSS selectors — everything else is left untranslated.

You can whitelist more than one block (this version replaces the function above, keep only one of them):

weglot_exclude_blocks

The opposite of the whitelist: add CSS selectors whose content must not be translated. Weglot marks every matching element with a data-wg-notranslate attribute.

Weglot always appends a set of built-in selectors to this list (for example #wpadminbar, .material-icons, and WooCommerce/Query Monitor selectors when those plugins are active). Your custom selectors are added on top of them.

JSON responses

weglot_add_json_keys

Weglot also translates JSON response but not all values. Use this filter to target specific values.

Argument
Type
Description

$keys

array

Array of string

The JSON values translated by default are:

  • Value with key: "name"

  • Value with key: "description"

  • Value in HTML format

Use case

You may come across values used in your JSON that are not translated by default. Here's an example using the message value:

To do this, we use weglot_add_json_keys filter.

Also, note that if a URL is detected in a value of the JSON, it will be replaced by the URL with the language code if and only if its key is exactly redirecturl, url or link. Keys are case-sensitive: redirectURL is not rewritten. For example, if your original JSON is

The translated response would be

Adding keys to check when replacing URL is done with weglot_ajax_replace_urls (add redirectURL there to have it rewritten too).

If you want to remove some defaults keys you can use the filter list_json_ld_keys

Through this filter, it is possible to remove existing keys and add new ones. In this example, the name key is explicitly removed from the array using array_search() and unset(). After that, a new key called message is added to the list.

This approach allows you to customize the structure of the JSON-LD data by excluding unwanted keys (such as name) and including alternative ones depending on your needs.

Escaping content from translation

These filters "shield" parts of your markup from the parser: their content is tokenized before translation and restored afterwards. Use them when a script, template or attribute must be left exactly as-is.

The following filters take an array and return the modified array:

Filter
Default
Purpose

weglot_escape_attributes

[]

HTML attribute names whose values must not be translated

weglot_escape_script_types

text/template, text/html, text/x-template, text/x-handlebars-template

<script type="…"> values whose content is escaped

weglot_escape_script_ids

tmpl-*, nf-*, *-js-extra

<script> id patterns to escape (* wildcard supported)

weglot_escape_script_classes

[]

<script> class patterns to escape (* wildcard supported)

weglot_escape_script_contains

[]

Escape scripts whose inner content matches a pattern

The following filters are simple on/off toggles (return true to enable, default false):

Filter
Purpose

weglot_escape_script_templates

Escape <script> template blocks before translation

weglot_escape_vue_js

Escape Vue.js attributes

weglot_escape_attribute_in_html

Escape configured attributes in HTML responses

weglot_escape_attribute_in_json

Escape configured attributes in JSON responses

The lists only take effect once their toggle is on: weglot_escape_attributes needs weglot_escape_attribute_in_html (HTML pages) or weglot_escape_attribute_in_json (JSON responses), and the four weglot_escape_script_* lists need weglot_escape_script_templates.

Modifying the final output

These filters let you edit the fully translated response, right before it is sent to the browser. Use them as a last resort, when no detection filter fits.

weglot_html_treat_page

A very powerful filter that allows you to make manual edition on the final translated DOM in PHP.

Argument
Type
Description

$html

string

HTML content of translated page

Use case 1

The following code replaces all of the "https://codex.wordpress.org/" links with "https://codex.wordpress.org/fr:Accueil" in the translated versions.

Use case 2

In this example, the replacement occurs according to the chosen language.

weglot_json_treat_page / weglot_xml_treat_page

Same idea as weglot_html_treat_page, but for the other response types. Each one receives the final translated string and must return the modified string:

  • weglot_json_treat_page — final translated JSON response.

  • weglot_xml_treat_page — final translated XML response (for example a sitemap).

weglot_render_dom

Same as weglot_html_treat_page, except the language button HTML is already included and the links are already translated. Handy when you need to act on the exact markup that will be rendered.

Client-side (dynamic) translation

All the filters in this section only take effect when weglot_translate_dynamics returns true. They configure Weglot's front-end JavaScript library — not the server-side PHP parser — and are used to translate content that changes after the initial page load.

1. Enabling Dynamic Content Translation

To enable the use of dynamic content translation on your website, add the following filter:

This filter allows Weglot to handle the translation of dynamic content, which may change after the initial page load (e.g., content updated via JavaScript).

2. Defining Custom Selectors

Next, define the selectors that Weglot should use to identify dynamic content. We achieve this by creating a custom function:

  • The function custom_weglot_dynamics_selectors() returns an array of CSS selectors. These selectors specify which parts of your website's content should be treated as dynamic.

  • For example, .wp-block-woocommerce-cart and .wp-block-woocommerce-checkout target WooCommerce cart and checkout blocks.

3. Applying Custom Selectors to Weglot Filters

To use the custom selectors defined above, apply them to both the dynamic and whitelist selector filters:

  • weglot_dynamics_selectors: This filter allows Weglot to recognize dynamic content based on the selectors you defined.

  • weglot_whitelist_selectors: This filter specifies elements that Weglot should always translate, ensuring that the specified content is included in translations.

By using the same function for both filters, you can reuse the list of selectors for both dynamic and whitelisted content.

4. Specifying URLs for Applying Custom Translations

Lastly, define where your custom dynamic translations should be applied. By default, this is set to an empty value, but you can configure it to apply to all URLs or a specific list:

  • weglot_allowed_urls: This filter determines on which URLs the custom translation rules will be applied.

  • Setting the value to 'all' ensures that your custom selectors will work on every page of your website. You can also pass an array of specific URLs if you only want the rules to apply to certain pages.

5. Proxifying iframes and URLs

Two more front-end filters let you route content through Weglot when needed:

  • weglot_proxify_iframes — list iframe selectors (same ['value' => '…'] shape as above) whose content should be handled by the JS library. Default empty.

  • weglot_proxify_urls — list resource URLs that should be routed through the Weglot proxy on translated pages. Default empty.

6. Excluding blocks from dynamic translation

weglot_excluded_blocks_selectors lists the blocks the JavaScript engine must leave untranslated, using the same ['value' => '…'] shape as the selectors above.

Since Weglot 6.3 it defaults to [ ['value' => 'address'] ]. Postal addresses rendered client-side — the WooCommerce block cart and block checkout, for instance — never go through the PHP parser, so the server-side address exclusion cannot reach them.

Return an empty array to translate everything, <address> tags included.

Unlike the server-side weglot_exclude_blocks, which a non-empty weglot_parser_whitelist disables entirely, these client-side exclusions still apply inside whitelisted and dynamic blocks. That is what makes the address default effective on the WooCommerce checkout even though .wc-block-checkout is whitelisted.

7. External JavaScript Dependency for Custom Code

When using the dynamic code, it requires an external JavaScript script to be loaded correctly for it to function as expected.

Key Considerations:

  1. Script Loading: If the external script fails to load or is not included properly on the page, the custom code will not work. Make sure that the script is loaded before the code is executed.

  2. defer Attribute Issues: If the external script is loaded with the defer attribute, it may cause unexpected behavior or delays, especially if your custom code depends on the script being fully available before execution.

  3. Solution: To ensure that your custom code works seamlessly, you may need to exclude this specific script from being deferred. This way, the script will load immediately and be available when your code is executed, avoiding potential timing issues.

Advanced parser tuning

Low-level filters you should only need in edge cases (very large pages, PCRE limits, custom parser configuration). Each returns the same type it receives.

Filter
Type
Default
Purpose

weglot_parser_config_provider

object

ServerConfigProvider

Swap the parser's ConfigProvider (must implement ConfigProviderInterface)

weglot_regex_tags_limit

int

200000

Max tag length before data-link URL rewriting is skipped. Only applied if a callback is registered, and only below weglot_length_replace_tags, which skips longer tags first

weglot_length_replace_a

int

1500

Max URL length considered for <a> link replacement; longer URLs are skipped to avoid PCRE errors

weglot_length_replace_tags

int

2000

Max surrounding-tag length for link replacement; longer tags are skipped

Last updated