我目前正在重写一个小插件,向访问者显示一个小信息文本。这个插件到目前为止是德语的,所以我想添加多语言支持,因为我正在处理一个应该是英语和德语的页面。可以在插件的设置界面中设置显示给访问者的文本。给定值存储在数据库中的单个选项中。在修改后的插件中,我将设置存储在单独的选项中,每个选项对应一种语言。我添加了一个$_GET
在设置注册中使用的参数,用于为特定于语言的选项创建唯一名称。
我的插件类的重要(精简)部分:
class Privacy_Policies {
// the language to which the text is translated
public $translation;
// the options, stored in the database
public $options;
public function __construct() {
// use the current user locale as a fallback
$this->translation = isset($_GET[\'lang\']) ? $_GET[\'lang\'] : get_user_locale();
// if an option already exists, edit it
// use $this->translation to determine the right language
$this->options = get_option(\'privacy_policies_\' . $this->translation);
// call registration when settings page gets loaded
add_action(\'admin_init\', array($this, \'register_settings\');
// create the settings page
add_action(\'admin_menu\', array($this, \'add_settings_page\');
}
// settings validation, called as callback to register settings
public function validate_settings($value) {
if (isset($value[\'checkbox\']) && 1 == $value[\'checkbox\']) {
$value[ \'checkbox\' ] = 1;
} else {
$value[ \'checkbox\' ] = 0;
}
$value[\'notice\'] = normalize_whitespace($value[\'notice\' ]);
$value[\'error_message\'] = normalize_whitespace($value[\'error_message\']);
$value[\'style\'] = normalize_whitespace($value[\'style\']);
return $value;
}
// register a distinct option name for each language
// the function is called when the settings page gets loaded
public function register_settings() {
register_setting(
\'privacy_notice_settings_group\',
\'privacy_notice_settings_\' . $this->translation,
array( $this, \'validate_settings\' )
);
}
// create the html for the settings page
// stripped down to a simple checkbox
public function get_settings_page() { ?>
<h2><?php echo $this->get_plugin_data(\'Name\'); ?></h2>
<form method="post" action="options.php">
<?php settings_fields(\'privacy_notice_settings_group\'); ?>
<table class="form-table">
<tr valign="top">
<td>
<!-- important: \'name\' must reflect the option name! -->
<input type="checkbox" id="privacy_checkbox" name="privacy_notice_settings_<?php echo $this->translation ?>[checkbox]" value="1"
<?php if (isset($this->options[\'checkbox\'])) {
checked(\'1\', $this->options[\'checkbox\']);
} ?> />
</td>
</tr>
</table>
</form>
<?php }
// add settings page
// called in the admin_menu hook
public function add_settings_page() {
add_options_page(
\'Privacy Policies Settings\',
\'Privacy Policies\',
\'manage_options\',
\'privacy_notice_settings_group\',
array( $this, \'get_settings_page\' )
);
}
}
有趣的是,无论在什么地方
$this->locale
设置将
always 作为WP当前语言环境的设置存储在数据库中(
get_user_locale()
). 一、 e.由以下内容组成的设置名称
\'privacy_notice_settings_\' . $this->translation
神秘地重新组合到
\'privacy_notice_settings_\' . get_user_locale()
.我怀疑秘密藏在什么地方
options.php
表单正在调用的。但我似乎无法调试这个。