Localiztion in javascript

WordPress currently uses the gettext feature which is available in php but unfortunately not in Javascript.
I have searched this matter on the web and have come up with this trick. But there is a problem as the php file needs to be called through WordPress system for the gettext feature to kick in.
I’m wondering if there is any way to call a php file inside WordPress so we can use the built-in functions and variables?
Or if anyone can come up with a better solution, that’d be super.

Related posts

Leave a Reply

1 comment

  1. WordPress has a nice function mainly for that wp_localize_script

    To use it first queue your script:

    wp_enqueue_script( 'My_Script_handle', 'path/to/script.js' );
    

    then create an array of strings you want to localize:

    $data = array( 
       'exit' => __( 'Exit','my-plugin-domain' ),
       'open' => __( 'Open','my-plugin-domain' ),
       'close' => __( 'Close','my-plugin-domain' ),
       'next' => __( 'Next','my-plugin-domain' ),
       'previous' => __( 'Previous','my-plugin-domain' )
    );
    

    and call it using wp_localize_script

    wp_localize_script( 'My_Script_handle', 'mystrings', $data );
    

    then you can access it in the page using JavaScript like this:

    alert(mystrings.exit);
    alert(mystrings.open);
    

    you get the Idea.