How to create translation ready shortcodes
I use many themes and plugins from other talented authors, but most of them are not French like me. That’s why each time i use a plugin or a theme from a non French developer, i have the same problem: shortcodes. Well, it’s not really a big problem for me because i speak English, but what about my French clients that don’t speak English at all? Imagine: they’re writing a post in French into their French version of the administration, and suddenly, when the time comes to insert a shortcode they have to insert it in English… Wow! That makes me feel bad. Their texts would then be similar to this:
“Il y a actuellement en ligne: [online_users] utilisateurs”.
Which means :
“At the moment [online_users] connected users”.
Imagine if you were having the same thing in English:
“At the moment [utilisateurs_connectes] connected users”.
I’m sorry, but writing the shortcode in another language isn’t user friendly at all because it’s not logic. So i decided to show you how to create a user friendly shortcode that can be used in any language. I’m talking about French, but that’s the same thing with every language!
The first step is to create a really simple plugin. Create a new folder under wp-content/plugins and name it: “translation-ready-shortcodes”. Then open it and create a new “index.php” file. Place this code :
This code simply creates the plugin, nothing more.
Here we are! The interesting part! In this step we need to register the shortcode. In my sample, i’m going to use this shortcode : [link to=”http://wordpress.org”]WordPress[/link]. The aim is to echo a simple link.
The basic code to do this is:
But the problem here, is that if a French guy uses this shortcode he will have to write “link” instead of “lien”, the French translation. So, what i want to do is to give this poor French guy the ability to write: [lien vers=”http://wordpress.org”]WordPress[/lien]. That would be much better.
To do so, i need to modify on the fly the shortcode itself (the tag), and the shortcode attributes (in this case, the word “to”). For the first one it’s easy, we simply need to use the __() function, but for the second one it’s more complex. We need to use a variable having a variable name. The code becomes:
That’s it! I mean for the code that’s it, now if you have to language file you can try to switch from one language to another… that works! It means that a English guy will use:
and a French guy will use:
while an Italian guy will do:
Isn’t it great?