我正在創建一個自定義 wordpress 插件,但在嘗試進行翻譯時,遇到了這個問題。對我來說一切都是正確的。
例如:插件檔案夾名稱“translated_plugin”和主檔案“translated_plugin.php”
<?php
/**
* Plugin Name: Translated Plugin
* Plugin URI: https://example.com
* Description: Example Plugin Description
* Version: 1.0.0
* Author: dev
* Author URI: https://example.com
* License: GPL-2.0
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: translated_plugin
* Domain Path: /languages
*/
if ( !defined( 'WPINC' ) ) {
die;
}
require __DIR__ . '/vendor/autoload.php';
$app = new Application();
register_activation_hook( __FILE__, [$app, 'activate'] );
register_deactivation_hook( __FILE__, [$app, 'deactivate'] );
示例“class_Application”類
class Application {
public function __construct() {
add_action( 'init', [$this, 'translate_it'] );
echo __('Test Text', 'translated_plugin');
}
public function translate_it(){
$loaded = load_plugin_textdomain( 'translated_plugin', false, dirname(dirname( plugin_basename( __FILE__ ) )) . '/languages/' );
// $loaded returns true when vardump($loaded), means textdomain path is correct and domain is loaded
}
}
在語言檔案夾中,pot 檔案“translated_plugin.pot”由 loco translate 插件生成。并且 .mo 檔案也是通過 loco translate 插件的翻譯程序生成的。但文本不會根據 WordPress 設定中的語言而改變。
(測驗主題上的類似程序正常作業,但不確定為什么即使翻譯檔案正確,檔案名與文本域相同,加載也是正確的,為什么不能用于插件)這里可能有什么問題,或者可能是來自 WordPress 的錯誤?謝謝!
uj5u.com熱心網友回復:
OP 更新代碼后編輯:
好的,現在我看到了:那個 echo 命令發生在translate_it()火災之前。該add_action()函式將函式添加到佇列中以在init操作設定為觸發時觸發,但這不是立即的。嘗試將您的 echo 命令放在下面的translate_it()函式中load_plugin_textdomain()。
class Application {
public function __construct() {
add_action( 'init', [$this, 'translate_it'] );
echo __('Test Text', 'translated_plugin'); //Will fire before text domain is loaded
}
public function translate_it(){
$loaded = load_plugin_textdomain( 'translated_plugin', false, dirname(dirname( plugin_basename( __FILE__ ) )) . '/languages/' );
// $loaded returns true when vardump($loaded), means textdomain path is correct and domain is loaded
echo __('Test Text', 'translated_plugin'); //Will fire after text domain is loaded
}
}
如果您想了解事件的順序,請按照以下方式進行
- WordPress 啟動
- WordPress 加載插件
$app = new Application();發生運行 __construct() 函式add_action( 'init', [$this, 'translate_it'] );將函式添加到佇列中- 回顯“測驗文本”
- WordPress做了一些其他的事情......
- WordPress 到達
do_action( 'init' ); - 現在你的
translate_it()函式運行,加載文本域
原始答案(現已過時):
看起來您正在使用兩個不同的文本域:translated_plugin在您的__()通話中和adev_translated_plugin在您的load_plugin_textdomain()通話中。我相當肯定那些需要是相同的。似乎您打算adev_translated_plugin在所有地方使用,這可能是最好的選擇。所以這會讓你的建構式看起來像這樣:
public function __construct() {
add_action( 'init', [$this, 'translate_it'] );
echo __('Test Text', 'adev_translated_plugin');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/439946.html
標籤:php WordPress wordpress 插件创建
