Hi,
I would appreciate an advice for this scenario.
I use different JS scripts in a multilingual site (Analytics, GDPR, ....), and there's not a simple way to assign a different code/language.
I have checked some Header/Footer injector plugins, but all of them are not translatable.
I thought it would be interesting to create a Types Custom Post "Snippets" and inject this scripts on Header or Footer as needed.
This way I could "translate" the snippet with WPML and have a different snippet code/language.
Does that makes sense?
Do you have a code I can use to inject the codes or a plugin suggestion?
Thanks
Best
It sounds like you want to enqueue different JavaScript files depending on the current language of the site. Is that correct? If so you can accomplish this in a child theme's functions.php file using the WPML language code constant. Use wp_enqueue_script to enqueue those files appropriately, along with any dependencies. For example, let's say you have two scripts you want to enqueue only in the French language site:
- main-fr.js
- strings-fr.js
Both files have a dependency, 'jquery'. In functions.php you would enqueue these conditionally like this:
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
function my_theme_enqueue_scripts() {
// only enqueue these scripts on the french site
if( ICL_LANGUAGE_CODE == 'fr' ) {
wp_enqueue_script( 'my-js', get_stylesheet_directory_uri() . '/main-fr.js', ['jquery'], false);
wp_enqueue_script( 'my-strings-js', get_stylesheet_directory_uri(). '/strings-fr.js', ['jquery'], false, true );
}
}
I thought it would be interesting to create a Types Custom Post "Snippets" and inject this scripts on Header or Footer as needed.
How will you inject these scripts into the header or footer? I'm not sure I understand that part. If you're just using custom post types because you want to translate things with WPML, I'm concerned that managing script content in a post editor and in a translation editor will be difficult.