WordPress plugin translation


Plugin translation has never for me seemed an easy task, i could never quite follow the mish mash of differing information around the web, and none of the guides available ever seemed to answer the specifics of what i needed to know about setting up a plugin for translation.

Well a couple of months have passed since i last put my head down and read up on the translation process, and fortunately for me the persistance in grasping the technique has paid off, i’ve managed (well i hope) to grasp the fundamental points of how to prepare a plugin for translation, and additionally how to run through a translation process.

Those of who would just prefer to see example code can skip straight to the plugin download.

NOTE: This is intended for code literate users, those of you who can already code but just need a quick run down on how to utilise the translation functionality inside a plugin.

Firstly your plugin will need to register a text domain for performing translation tasks, you can read more on that here. Of course the codex entry does leave a little to be desired, not really giving much in the way of an easy to follow example.

However, let’s just run by the parameters for load_plugin_textdomain very briefly.

1. $domain

This is basically the name for your text domain. You’ll have to reference this alot in your plugin, so it certainly helps to make it something easy to remember and quick to type. The name (or domain) declared here will also prefix all translation files used in your plugin, so do try to KISS.

2. $abs_rel_path

We will ignore this parameter because it’s no longer used as of WordPress 2.7, originally you would use this parameter to declare the path to the language files in your plugin, based on the WordPress ABSPATH. I will not be using this parameter for the example, so i’ll stop there.

3. $plugin_rel_path

I think the codex description sums up what this parameter does pretty well (not perfect though).

Relative path to WP_PLUGIN_DIR. This is the preferred argument to use. It takes precendence over $abs_rel_path

Ok, so now the description is out of the way, where should you place the call to load_plugin_textdomain?

As far as i know textdomains should be registered at the init stage, so depending on whether you want to translate front side, admin side or both, will depend where you hook the registration onto, but for the sake of this example i’ve hooked mine onto admin_init.

Inside the main function of my plugin class is a line like so.

				// The action hook
				add_action( 'admin_init' , array( &$this , 'register_plugin_settings' ) );

Various other pieces of code are present in the functions, so to keep this blog trim here’s the line inside the above referenced function that registers the textdomain.

				// How the text domain looks inside the register plugin settings function referenced above
				load_plugin_textdomain(
					$this->l10n_prefix,                        // Plugin text domain reference
					false,                                     // False - deprecated parameter
					basename( dirname( __FILE__ ) ) . '/lang'  // Path to translation files
				);

In the case of my example plugin(at the end of this post) i’ve used a variable to store the name of the textdomain, this means i don’t have to keep remembering the reference name, i simply type in the variable each time i want to make some text translatable.

More information and a very similar example of load_plugin_textdomain can be found here.

Here’s my text domain variable for reference.

			$this->l10n_prefix = 'translatable_demo';

Also note the third parameter used in the text domain registration, this sets where to look for the translation files, you can however (as the codex entry suggests), leave this blank and WordPress will assume they reside in the same folder as your plugin. Of course it’s good to keep things organised, i know i do(just a little), so i’ve opted to have the text domain reference a folder called “lang” (no quotes) inside my plugin’s folder.

Ok you’ve come this far, you’ve registered a text domain, what next?

Next you’ll need to start converting all the strings in your plugin you wish to make translatable, and this is probably the most easiest step in the whole process, and rather then repeat the guides and information already available i’ll simply point you here, and provide a very brief example below based on my example plugin.

Example strings:

$var1 = 'WordPress';
echo 'Hello world';

Translation ready: (remembering the text domain name)

$var1 = __( 'WordPress', 'translatable_demo' ); // __() return value
_e( 'Hello world', 'translatable_demo'); // _e() - echoed value

That’s it as far as making the plugin translation ready, honestly, what more did you expect?

Techinically there is nothing left to do on your part, the plugin can be translated, but a good practice for plugin developers (or so i hear) is to include a .POT file along with the plugin. In the most simple terms this is a base translation file, that will in essence be like any translation of your plugin, but not include a translation for each string, providing a .POT file just means a translator can pick up that file and get translating without having to run your plugin’s folder/files through a translation program (you save them a few minutes, but it’s really very easy, and the process is pretty much identical to that of the translator).

You can download the example plugin here or here(sorry couldn’t host it here, not allowed zips on WordPress.com blogs).
EDIT (02/07/13): New download link(hopefully this one won’t just random expire)

For those of you still interested in learning how to create a .POT file and developing language files read on, i’m going to run down the procedure i followed for creating a .POT file. I’m a windows user, so those of you on another OS, you’ll unfortunately have to look toward existing guides on how to translate. Anyone still with me, read on..

  1. Download and Install Poedit (it’s free).
  2. Open Poedit and click on New Catalog, under File.
  3. Fill in a name for the project, and choose the appropriate language you write in (not required but i tend to do it anyway).
  4. Click on the Paths tab at the top of the box.
  5. Click the second little icon, and put the directory location of your plugin in, for example “C:\Documents and Settings\USER\Desktop\MY_PLUGIN”
  6. Click on the Keywords tab at the top of the box.
  7. Click the second icon, and enter “__” (no quotes, and that’s two underscores).
  8. Click the second icon again, this time entering “_e”
  9. Now click the Ok button.
  10. A save dialog will appear, so enter a name for your POT file and change the extension to .pot
  11. Choose an appropriate place to save the file (you’ll probably want to choose to the language folder inside your plugin).
  12. Click Save.
  13. Various things will happen now and poedit will shows some boxes on the screen. Don’t do anything, this is what a translator will see when he or she is translatin your POT file. Just close the file, job done.

NOTE: It’s most likely a good idea to name your POT file with the same prefix the translation files will require. The prefix is the name you gave you text domain inside your plugin, ie. the first parameter.

Doing translations is the easy part, so i’m leaving that out of my blog for now, but if anyone finds this useful and would like to see an additional “How to make a translation file” or similar, then post a comment, let me know.

If you struggled to keep up with anything covered above, or you think anything above could do with refinement, again feel free to provide feedback, i’m not the world’s best blogger, and my mind can wander when writing, so critique is most definately welcome..

Advertisements

33 thoughts on “WordPress plugin translation”

  1. Hi and thanks for few enlightements that article gave me! Can you give me any advice howto translate a plugin that is located in mu-plugins folder? I’m talking about this particular plugin which doesn’t have text_domain added, so I’ve added them to the code, but nothing seems to make the .mo file to load up..

    I’ve tried many variations of this line in the beginning of the php-file:
    load_plugin_textdomain( 'more-privacy', false, 'wp-content/mu-plugins/' );

    While the translated line looks like this:

    The .mo file is named ds_wp3_private_blog-fi_FI.mo while the plugin itself is ds_wp3_private_blog.php. Both reside in

    wp-content/mu-plugins

    and I’ve tried several names and moving the .mo file to

    wp-content/languages

    yet nothing seems to work. Any ideas? I’m running WP3.1 on the site. Or should I post my rant to support-forums or here?

    Thx in advance 🙂

  2. Hi,

    You may wish to check out the example plugin, it’s the most basic example of creating a translatable plugin i can give.

    Translation files must be named using the text domain name as the prefix, if you check out the example plugin you’ll see how the translation files are named in relation with the registered text domain name.

    Above you wrote your translation files are like..
    ds_wp3_private_blog-LANG.mo

    ..but then here you text domain name does not match the file name..

    load_plugin_textdomain( 'more-privacy' ...

    Based on that name your translation files should be…
    more-privacy-LANG.mo

    Where LANG of course represents the locale, eg. fr, en, etc…

  3. Hi! I’m having sopme major problems with this. I’ve been searching around like crazy but I just can’t get it to work. I create a pot file, load it into poedit, translate the phrases, generate a po file, generate a mo file from that, I use the domain “harledsfran” both in the code where the text is displayed “__(‘message’, ‘harledsfran’)”, when loading the text domain “load_plugin_textdomain (‘harledsfran’, false, basename (dirname (__FILE__)) . ‘/languages’);”, and in the file names “harledsfran-sv_SE.mo” and “harledsfran-sv_SE.po” and place those in the folder “languages” which is located in the plugin’s directory, but STILL, it’s just not working. Can you help me out a bit? I tried downloading the example to see if I did something wrong after all but the link is dead.

  4. Your style is really unique compared to other folks I have read
    stuff from. I appreciate you for posting when you’ve got
    the opportunity, Guess I will just book mark this site.
    You may buy real facebook fans from multiple vendors with inexpensive charges.

    buy likes 5000 Level of quality fans For jus $29.
    9 Conserve.
    Over the internet may how to get more likes on facebook at a discount?

  5. I will immediately seize your rss as I can not
    in finding your email subscription link or e-newsletter service.
    Do you’ve any? Kindly allow me realize in order that I could subscribe.
    Thanks.

  6. Hurrah, that’s what I was seeking for, what
    a data! present here at this webpage, thanks admin of this web page.
    cheap and effective instagram
    Trend to instagram is to get stars coordinator a post in your case.

    instagram it will probably be an extremely wise investment decision for your organization.

  7. Great delivery. Great arguments. Keep up the great spirit.
    In order to instagram followers towards your instagram consideration,
    there are many more efficient means.
    Shoppers could instagram followers through lots of reasonably priced expert services.

  8. Because the ways for beating a drug test focus on specific forms of drug
    tests, looking to pass a drug test lacking the
    knowledge oof what form of test you take is like trying to find
    something using thee lights turned off. Saliva test can detect drugs ingested within a short time.
    If the employee carries a prescription for a medication,
    it usually must be no more than half a year old.

  9. Купить конструктор Лего в Харькове все на складе срочная
    Доставка.
    При поиске лего или иного подарка в Киеве конструктора, многие родители заказывают конструктор Lego.

    Всегда дитя былуясь с лего не только весело проводит время , но
    и старается фантазировать широко.

    Конструкторы Лего помогают выбрать любую украинскую теорию в фантастическую картинку
    в размере фигурок и красок. Для совсем
    юных можно купить конструкторы,
    те что научат не только угадывать сложные
    формы и цвета , но и фантазировать.

    lego
    Огромные детали наборов выполнены
    в яркой расцветке и совместимы
    по разному собой. Из этих наборов можно складывать
    не такие предметы гарисованные в
    инструкции , но и придумать что-то новое
    непосторимое.
    У заказчиков иногда сложно записать вопрос
    : «Где приобрести конструктор Лего в Украине ?».
    Мы помогаем тебе совершить заказ в нашем площадке «Страна Пипец».
    Здесь вы получите качественное соровождение при очень высоких ценах.
    Позвонив себе по контактным телефонам , наши компетентные друзья помогут вам определиться с
    выбором конструктора Lego.
    Мы организовываем удобную
    доставку конструктора в города Одесса Чернигов

  10. I like the valuable info you provide in your articles.
    I will bookmark your blog and take a look at once more right here
    frequently. I’m moderately certain I will learn plenty of new stuff right right here!
    Best of luck for the following!

    – cadeau
    – cadeau
    – cadeau
    – cadeau
    – cadeau
    – cadeau

  11. I will immediately seize your rss feed as I can’t find your email
    subscription hyperlink or newsletter service. Do you have any?
    Kindly permit me understand in order that I may subscribe.
    Thanks.

  12. hi!,I love your writing so much! proportion we keep up a
    correspondence more approximately your post on AOL? I require a specialist on this house to solve my problem.

    Maybe that is you! Taking a look forward to peer you.

  13. Nice post. I learn something new and challenging on sites I stumbleupon every day.
    It’s always useful to read articles from other writers and practice something from their sites.

  14. It’s actually a great and helpful piece of information. I am happy that
    you just shared this helpful info with us. Please stay us up
    to date like this. Thanks for sharing.

  15. I think that what you said made a lot of sense. But, what
    about this?. twitter
    twitter
    twitter
    what if you added a little information?. twitter
    twitter
    I mean, I don’t want to tell you how to run your blog, however suppose you added a headline that grabbed a person’s attention?.
    twitter
    twitter
    twitter
    I mean WordPress plugin translation | 73105 is a little plain. You might peek at Yahoo’s front page and watch how they create article headlines to
    grab people interested. You might add a related video or a related pic
    or two to get people excited about everything’ve written. In my
    opinion, it might bring your blog a little livelier.

    twitter
    twitter
    twitter

  16. At the finish of tthe series you need to be able to hold your own at any tasting event.

    You should do secondary fermentation properly
    annd just for this, you should buy right wine making equipment.
    Alcohol and co2 is produced being a result.

  17. Thhe besat adviice for everyone who thinks thjat she orr he may
    have rosacea would be to seee a dermatologist aftsr possible.
    According to examine though, some emotions may cause breakouts for example anxiety, stress and fear.
    Rosacea, referred to as adult acne is a skkin problem which generdally affects those involved with their
    thirties or forties and typically individuals light complexion.

  18. Just want to say your article is as astounding.

    The clarity to your publish is just excellent and i could assume you are an expert
    on this subject. Fine along with your permission let me to seize your
    feed to stay updated with coming near near post. Thanks one million and please carry on the rewarding work.
    youtube
    youtube

  19. Definitely imagine that which you stated.
    Your favourite justification appeared to be onn the internet the simplest factor to bear in mind of.I say to you,
    I definitely get irked whilst people think about concerns
    that they just don’t recognize about. You managed to hit the nail upon the higheet and outlined out the entire thing without having
    side-effects , folks can take a signal. Will probably be
    again to get more. Thanks

  20. Hi fantastic website! Does running a blog such as this take
    a large amount of work? I have very little knowledge of computer programming but I had been hoping to start my own blog in the
    near future. Anyhow, if you have any ideas or techniques for new blog owners please share.
    I know this is off subject but I simply needed to ask.
    Thanks a lot!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s