0
votes

i have created a plugin "translation_test" to test the translation capabilities of wordpress.

Translation files

in the languages directory there is a file translation_test.pot that contains:

msgid "Testing"
msgstr ""

and a file translation_test-de_DE.po:

msgid "Testing"
msgstr "Das ist ein test"

using gettext i have created the corresponding .mo file with this command:

msgfmt translation_test-de_DE.po -o translation_test-de_DE.mo

i have uploaded all 3 files to the plugin's languages directory: ./translation_test/languages/

Plugin php file:

there is also an php file called "translation_test" where the textdomain is loaded and an admin page created to display the translated text:

<?php

/*
Plugin Name: translation_test
Plugin URI: 
Description: translation_test
Version: 1.0
Author: 
Author URI: 
Text Domain: translation_test
*/

function translation_test_init_textdomain()
{
    load_plugin_textdomain( 'translation_test', false, dirname( plugin_basename( '__FILE__' ) ) . '/languages/' );
}
add_action( 'init', 'translation_test_init_textdomain' );

/**
 * Register a custom menu page.
 */
function wpdocs_register_my_custom_menu_page(){
    add_menu_page( 'title','custom menu','manage_options','custompage','my_custom_menu_page','',6 ); 
}
add_action( 'admin_menu', 'wpdocs_register_my_custom_menu_page' );
 
function my_custom_menu_page()
{
    echo __( 'Testing', 'translation_test' );
}

?>

Language setting

in the admin area of wordpress i set the language to german and additionally i added the following line to the wp-config.php file:

define ('WPLANG', 'de_DE');

sadly the translation does not work and it always shows "Testing". does anyone know where the error is? is there some bare-bones plugin template that has a working translation that i could use a starting point?

1

1 Answers

1
votes

Try this:

//get User Locale
$user_locale = get_user_locale();

// load text domain and .mo file
load_textdomain('your_text_domain', $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/your_plugin/your_text_domain-'.$user_locale.'.mo');

// function to use with locale hook
function wpsx_redefine_locale($locale){
  global $user_locale;
  if ($user_locale == ''){
    return "en_US";
  } else {
    return $user_locale;
  }
}

// define locale hook
add_filter('locale','wpsx_redefine_locale',10);
// test translation
echo __('test','your_text_domain');

Obs: I use LOCO translate to manage my text domains and .mo and .po files. https://br.wordpress.org/plugins/loco-translate/