How to add translation to WordPress plugin

198

1- Add Text Domain and Domain Path to header:

/**
 * Plugin Name: Bookstore
 * Description: A plugin to manage books
 * Version: 1.0
 * Text Domain: bookstore
 * Domain Path: /languages
 */

2- Load the Text Domain in Plugin Code

In your main plugin file (e.g., bookstore.php):

add_action('plugins_loaded', function() {
    load_plugin_textdomain('bookstore', false, dirname(plugin_basename(__FILE__)) . '/languages');
});

3- Generate the .pot File

create folder “languages” in your plugin . e.g wp-content/plugins/bookstore/languages

cd to the wp-content/plugins/bookstore path and run cli command: wp i18n make-pot . languages/bookstore.pot

4- Create bookstore-fa_IR.po manually in the folder “languages” and write your translations:

msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Language: fa_IR\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: includes/admin-page.php:10
msgid "Book Title"
msgstr "عنوان کتاب"

#: includes/admin-page.php:11
msgid "Author"
msgstr "نویسنده"

#: includes/admin-page.php:12
msgid "Price"
msgstr "قیمت"

5 – Compile .po to .mo

cd to languages path and run cli command: msgfmt bookstore-fa_IR.po -o bookstore-fa_IR.mo

Maybe you need to install gettext GNU : sudo apt install gettext (without gettext, the msgfmt won’t work).