Skip Navigation

This is the technical support forum for WPML - the multilingual WordPress plugin.

Everyone can read, but only WPML clients can post here. WPML team is replying on the forum 6 days per week, 22 hours per day.

This topic contains 3 replies, has 2 voices.

Last updated by Nicolas V. 1 year, 10 months ago.

Assisted by: Nicolas V..

Author Posts
July 14, 2023 at 4:31 pm #14040867

andrewT-18

Hi,

I would like to add a piece of javascript, but ONLY to our english pages. We elected to not have the english pages be /en, they are just the root domain. But, we do NOT want this javascript to display on any translated pages (/fr, /es, etc). Is there a way to do this?

In the future, we would also add Javascript only to specific language databases (/fe, /es, etc). So we would need to understand how to do both.

Thank you!

July 14, 2023 at 5:10 pm #14041013

Nicolas V.
Supporter

Languages: English (English ) French (Français )

Timezone: America/Lima (GMT-05:00)

Hello,

Welcome to the WPML support forum.
You can use our hook 'wpml_current_language' to get the current language and then use an IF statement to add your JS only if the language is EN.

Ref: https://wpml.org/wpml-hook/wpml_current_language/

Quick example:

<?php 
$my_current_lang = apply_filters( 'wpml_current_language', NULL );
if ( $my_current_lang == 'en' ) { echo '<p>English content</p>'; };
?>
July 17, 2023 at 2:49 pm #14050733

andrewT-18

Ok cool thank you, A couple more questions:

1. If I wanted to add my javascript into that "quick example" where would I put it? The script is from a source URL like this: <script src="fake-url"></script>
2. How would this script change for other languages? Do I just change out the "my_current_lang" section?

Thank you!

July 17, 2023 at 9:30 pm #14053637

Nicolas V.
Supporter

Languages: English (English ) French (Français )

Timezone: America/Lima (GMT-05:00)

Hello,

You can use IF / ELSEIF statements for all your languages.
Here is an example:
Code to be inserted in your functions.php

add_action( 'wp_head', function(){
$my_current_lang = apply_filters( 'wpml_current_language', NULL );

if( $my_current_lang == 'en' ){ ?>
<script src="fake-url-ENGLISH"></script>

<?php } elseif( $my_current_lang == 'it' ){ ?>
<script src="fake-url-ITALIAN"></script>

<?php } elseif( $my_current_lang == 'fr' ){ ?>
<script src="fake-url-FRENCH"></script>

<?php } 
});