Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
1  
Hope you don't mind the edit :) - just wanted to make it obvious the language domain is needed. –  Stephen Harris Mar 25 '12 at 19:20
    
Thanks, this is actually a better way. I was using wp_localize_script for ajax url, but it didn't come to my mind that I can use it for l10n. –  Hamed Momeni Mar 25 '12 at 19:51
    
This one's one of the extremely good and well done answers! +1! –  kaiser Mar 25 '12 at 22:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.