Skip Navigation

[Resolved] Types as Script Injector

This support ticket is created 5 years, 8 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

Tagged: 

This topic contains 1 reply, has 2 voices.

Last updated by Christian Cox 5 years, 8 months ago.

Assisted by: Christian Cox.

Author
Posts
#1233775

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

#1233918

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.