Skip to content

Instantly share code, notes, and snippets.

@webdados
Last active September 19, 2017 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdados/0285a5a65e67782101ee724e6617a964 to your computer and use it in GitHub Desktop.
Save webdados/0285a5a65e67782101ee724e6617a964 to your computer and use it in GitHub Desktop.
Localize own Javascript with WPML current language (icl_vars was removed in 3.8)
<?php
add_action('wp_enqueue_scripts', 'my_scripts');
function my_scripts() {
// Add your JS file
wp_enqueue_script( 'my_script', get_template_directory_uri().'/js/functions.js' );
// Localize your script with server side data
global $sitepress;
wp_localize_script( 'my_script', 'my_var', array(
'wpml_current_language' => $sitepress->get_current_language(), //On javascript use my_var.wpml_current_language to get this value
'any_other_var' => 'any_other_value', //On javascript use my_var.any_other_var to get this value
) );
}
@s3rgiosan
Copy link

s3rgiosan commented Sep 19, 2017

Now with WordPress Coding Standards 😅

    add_action( 'wp_enqueue_scripts', 'my_scripts' );
    function my_scripts() {

        // Localize your script with server side data.
        global $sitepress;

        // Add your JS file.
        wp_enqueue_script( 'my_script', get_template_directory_uri() . '/js/functions.js' );

        $data = array(
            'any_other_var' => 'any_other_value',
        );

        if ( ! empty( $sitepress->get_current_language() ) ) {
            $data['wpml_current_language'] = $sitepress->get_current_language();
        }

        wp_localize_script( 'my_script', 'my_var', $data );
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment