文章目录[隐藏]
WordPress柔性供应链软件的多语言与本地化支持教程
引言:全球化时代的供应链管理需求
在当今全球化商业环境中,企业供应链往往跨越多个国家和地区。WordPress作为全球最流行的内容管理系统,其供应链管理插件也需要具备强大的多语言和本地化支持能力。本文将详细介绍如何为WordPress柔性供应链软件实现完整的国际化(i18n)和本地化(l10n)支持,帮助您的插件适应不同语言和地区的用户需求。
多语言支持基础架构
1. WordPress国际化框架
WordPress提供了完整的国际化框架,使用gettext作为翻译系统。以下是基础的多语言支持代码结构:
<?php
/**
* 柔性供应链插件多语言支持主文件
* Plugin Name: Flexible Supply Chain
* Text Domain: flexible-supply-chain
* Domain Path: /languages
*/
// 初始化插件时加载文本域
add_action('plugins_loaded', 'fsc_load_textdomain');
function fsc_load_textdomain() {
// 加载插件语言文件
load_plugin_textdomain(
'flexible-supply-chain', // 文本域,必须与插件头信息一致
false, // 已弃用参数
dirname(plugin_basename(__FILE__)) . '/languages/' // 语言文件路径
);
}
// 在管理界面也确保加载文本域
add_action('admin_init', 'fsc_load_admin_textdomain');
function fsc_load_admin_textdomain() {
if (is_admin()) {
load_plugin_textdomain('flexible-supply-chain', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
}
?>
2. 准备翻译字符串
在插件代码中,所有需要翻译的字符串都应该使用特定的函数进行包装:
<?php
/**
* 供应链订单管理类示例
*/
class FSC_Order_Manager {
public function display_order_status($order_id) {
// 使用__()函数进行字符串翻译(返回翻译后的字符串)
$status_label = __('Order Status', 'flexible-supply-chain');
// 使用_e()函数直接输出翻译内容
echo '<h3>' . esc_html($status_label) . '</h3>';
$status = get_post_meta($order_id, '_order_status', true);
// 使用带上下文的翻译
$status_text = '';
switch($status) {
case 'pending':
// _x()函数提供上下文信息,帮助翻译者理解字符串使用场景
$status_text = _x('Pending', 'order status', 'flexible-supply-chain');
break;
case 'processing':
$status_text = _x('Processing', 'order status', 'flexible-supply-chain');
break;
case 'shipped':
$status_text = _x('Shipped', 'order status', 'flexible-supply-chain');
break;
case 'delivered':
$status_text = _x('Delivered', 'order status', 'flexible-supply-chain');
break;
default:
$status_text = _x('Unknown', 'order status', 'flexible-supply-chain');
}
// 使用printf和翻译函数处理带变量的字符串
printf(
/* translators: %1$s: 订单ID, %2$s: 订单状态 */
__('Order #%1$s is currently %2$s.', 'flexible-supply-chain'),
$order_id,
$status_text
);
// 使用_n()处理单复数形式
$item_count = $this->get_order_item_count($order_id);
$item_message = sprintf(
_n(
'This order contains %d item.', // 单数形式
'This order contains %d items.', // 复数形式
$item_count, // 数量
'flexible-supply-chain' // 文本域
),
$item_count
);
echo '<p>' . esc_html($item_message) . '</p>';
}
private function get_order_item_count($order_id) {
// 模拟获取订单商品数量
return 5;
}
}
?>
创建语言文件
1. 生成POT模板文件
POT文件是翻译的模板文件,包含所有需要翻译的字符串。您可以使用以下工具生成:
# 使用WP-CLI生成POT文件
wp i18n make-pot /path/to/your/plugin /path/to/your/plugin/languages/flexible-supply-chain.pot
# 或者使用Poedit软件手动创建
2. 创建翻译文件
为每种语言创建PO和MO文件。例如,创建中文翻译:
- 复制
flexible-supply-chain.pot为flexible-supply-chain-zh_CN.po - 使用Poedit或类似工具翻译所有字符串
- 保存后会自动生成
flexible-supply-chain-zh_CN.mo文件
3. 语言文件目录结构
your-plugin/
├── flexible-supply-chain.php
├── languages/
│ ├── flexible-supply-chain.pot # 翻译模板
│ ├── flexible-supply-chain-zh_CN.po # 中文翻译源文件
│ ├── flexible-supply-chain-zh_CN.mo # 中文编译文件
│ ├── flexible-supply-chain-fr_FR.po # 法语翻译源文件
│ └── flexible-supply-chain-fr_FR.mo # 法语编译文件
└── ...
高级本地化功能实现
1. 地区特定的日期和货币格式
<?php
/**
* 供应链本地化工具类
*/
class FSC_Localization_Helper {
/**
* 根据地区格式化日期
* @param string $date 原始日期
* @param string $locale 地区代码
* @return string 格式化后的日期
*/
public static function format_localized_date($date, $locale = '') {
if (empty($locale)) {
$locale = get_locale(); // 获取当前WordPress地区设置
}
$timestamp = strtotime($date);
// 根据地区设置日期格式
$date_formats = array(
'en_US' => 'F j, Y', // December 25, 2023
'zh_CN' => 'Y年m月d日', // 2023年12月25日
'fr_FR' => 'j F Y', // 25 décembre 2023
'de_DE' => 'j. F Y', // 25. Dezember 2023
);
$format = isset($date_formats[$locale]) ?
$date_formats[$locale] :
get_option('date_format');
return date_i18n($format, $timestamp);
}
/**
* 根据地区格式化货币
* @param float $amount 金额
* @param string $currency 货币代码
* @param string $locale 地区代码
* @return string 格式化后的货币字符串
*/
public static function format_localized_currency($amount, $currency = 'USD', $locale = '') {
if (empty($locale)) {
$locale = get_locale();
}
// 货币符号映射
$currency_symbols = array(
'USD' => '$',
'EUR' => '€',
'GBP' => '£',
'CNY' => '¥',
'JPY' => '¥',
);
$symbol = isset($currency_symbols[$currency]) ?
$currency_symbols[$currency] :
$currency;
// 根据地区设置货币格式
$formats = array(
'en_US' => '%s%.2f', // $100.00
'zh_CN' => '%s%.2f', // ¥100.00
'fr_FR' => '%.2f %s', // 100.00 €
'de_DE' => '%.2f %s', // 100.00 €
);
$format = isset($formats[$locale]) ?
$formats[$locale] :
'%s%.2f';
// 千位分隔符和小数点处理
$decimal_separator = (strpos($locale, 'fr') === 0 || strpos($locale, 'de') === 0) ? ',' : '.';
$thousands_separator = (strpos($locale, 'fr') === 0 || strpos($locale, 'de') === 0) ? ' ' : ',';
$formatted_amount = number_format(
$amount,
2,
$decimal_separator,
$thousands_separator
);
return sprintf($format, $symbol, $formatted_amount);
}
}
?>
2. 动态内容翻译
对于数据库中的动态内容(如产品名称、供应商信息),需要实现翻译管理系统:
<?php
/**
* 供应链产品多语言支持
*/
class FSC_Product_Translator {
/**
* 获取产品的翻译
* @param int $product_id 产品ID
* @param string $field 字段名
* @param string $locale 目标语言
* @return string 翻译后的内容
*/
public static function get_translated_product_field($product_id, $field, $locale = '') {
if (empty($locale)) {
$locale = get_locale();
}
// 默认语言的内容
$default_value = get_post_meta($product_id, $field, true);
// 如果请求的是默认语言,直接返回
$default_locale = apply_filters('fsc_default_locale', 'en_US');
if ($locale === $default_locale) {
return $default_value;
}
// 获取翻译后的内容
$translation_key = $field . '_translation_' . $locale;
$translated_value = get_post_meta($product_id, $translation_key, true);
// 如果没有翻译,返回默认内容
return empty($translated_value) ? $default_value : $translated_value;
}
/**
* 保存产品字段的翻译
* @param int $product_id 产品ID
* @param string $field 字段名
* @param array $translations 翻译数组 [locale => translation]
* @return bool 是否保存成功
*/
public static function save_product_translations($product_id, $field, $translations) {
foreach ($translations as $locale => $translation) {
$translation_key = $field . '_translation_' . $locale;
update_post_meta($product_id, $translation_key, sanitize_text_field($translation));
}
return true;
}
/**
* 在前端显示本地化的产品信息
*/
public static function display_localized_product($product_id) {
$current_locale = get_locale();
// 获取本地化的产品信息
$name = self::get_translated_product_field($product_id, 'product_name', $current_locale);
$description = self::get_translated_product_field($product_id, 'product_description', $current_locale);
$specifications = self::get_translated_product_field($product_id, 'product_specifications', $current_locale);
// 显示产品
echo '<div class="fsc-product">';
echo '<h2>' . esc_html($name) . '</h2>';
echo '<div class="description">' . wpautop(esc_html($description)) . '</div>';
echo '<div class="specifications">' . wpautop(esc_html($specifications)) . '</div>';
echo '</div>';
}
}
?>
管理界面多语言支持
1. 创建翻译管理界面
<?php
/**
* 供应链翻译管理页面
*/
class FSC_Translation_Admin {
public function __construct() {
add_action('admin_menu', array($this, 'add_translation_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
/**
* 添加翻译管理菜单
*/
public function add_translation_menu() {
add_submenu_page(
'edit.php?post_type=fsc_product', // 父菜单(供应链产品)
__('Translations', 'flexible-supply-chain'), // 页面标题
__('Translations', 'flexible-supply-chain'), // 菜单标题
'manage_options', // 权限
'fsc-translations', // 菜单slug
array($this, 'render_translation_page') // 回调函数
);
}
/**
* 渲染翻译管理页面
*/
public function render_translation_page() {
?>
<div class="wrap">
<h1><?php _e('Supply Chain Translations', 'flexible-supply-chain'); ?></h1>
<div class="fsc-translation-manager">
<div class="fsc-language-selector">
<h2><?php _e('Select Language', 'flexible-supply-chain'); ?></h2>
<select id="fsc-target-language">
<option value="zh_CN"><?php _e('Chinese (Simplified)', 'flexible-supply-chain'); ?></option>
<option value="fr_FR"><?php _e('French', 'flexible-supply-chain'); ?></option>
<option value="de_DE"><?php _e('German', 'flexible-supply-chain'); ?></option>
<option value="es_ES"><?php _e('Spanish', 'flexible-supply-chain'); ?></option>
<option value="ja_JP"><?php _e('Japanese', 'flexible-supply-chain'); ?></option>
</select>
</div>
<div class="fsc-translation-editor">
<h2><?php _e('Translation Editor', 'flexible-supply-chain'); ?></h2>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php _e('Original Text', 'flexible-supply-chain'); ?></th>
<th><?php _e('Translation', 'flexible-supply-chain'); ?></th>
<th><?php _e('Context', 'flexible-supply-chain'); ?></th>
</tr>
</thead>
<tbody id="fsc-translation-strings">
<!-- 通过AJAX加载翻译字符串 -->
</tbody>
</table>
<button id="fsc-save-translations" class="button button-primary">
<?php _e('Save Translations', 'flexible-supply-chain'); ?>
</button>
</div>
</div>
</div>
<?php
}
/**
* 加载管理界面脚本
*/
public function enqueue_admin_scripts($hook) {
if ($hook !== 'fsc-product_page_fsc-translations') {
return;
}
wp_enqueue_script(
'fsc-translation-admin',
plugins_url('js/translation-admin.js', __FILE__),
array('jquery'),
'1.0.0',
true
);
wp_localize_script('fsc-translation-admin', 'fsc_translation_data', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('fsc_translation_nonce'),
'strings' => array(
'saving' => __('Saving...', 'flexible-supply-chain'),
'saved' => __('Translations saved successfully!', 'flexible-supply-chain'),
'error' => __('Error saving translations.', 'flexible-supply-chain'),
)
));
wp_enqueue_style(
'fsc-translation-admin',
plugins_url('css/translation-admin.css', __FILE__)
);
}
}
// 初始化翻译管理
new FSC_Translation_Admin();
?>
前端语言切换器
1. 创建语言切换小工具
<?php
/**
* 供应链语言切换小工具
*/
class FSC_Language_Switcher_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'fsc_language_switcher',
__('Supply Chain Language Switcher', 'flexible-supply-chain'),
array('description' => __('Allow users to switch languages for supply chain content', 'flexible-supply-chain'))
);
}
/**
* 前端显示小工具
*/
public function widget($args, $instance) {
echo $args['before_widget'];
if (!empty($instance['title'])) {
echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
}
$this->render_language_switcher();
echo $args['after_widget'];
}
/**
* 渲染语言切换器
*/
private function render_language_switcher() {
$available_languages = apply_filters('fsc_available_languages', array(
'en_US' => __('English', 'flexible-supply-chain'),
'zh_CN' => __('中文', 'flexible-supply-chain'),
'fr_FR' => __('Français', 'flexible-supply-chain'),
'de_DE' => __('Deutsch', 'flexible-supply-chain'),
'es_ES' => __('Español', 'flexible-supply-chain'),
));
$current_language = get_locale();
$current_url = remove_query_arg('fsc_lang');
echo '<ul class="fsc-language-switcher">';
foreach ($available_languages as $code => $name) {
$url = add_query_arg('fsc_lang', $code, $current_url);
$class = ($code === $current_language) ? 'current-language' : '';
printf(
'<li class="%s"><a href="%s" data-lang="%s">%s</a></li>',
esc_attr($class),
esc_url($url),
esc_attr($code),
esc_html($name)
);
}
echo '</ul>';
}
/**
* 小工具后台表单
*/
public function form($instance) {
$title = !empty($instance['title']) ? $instance['title'] : '';
?>
<p>
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
<?php _e('Title:', 'flexible-supply-chain'); ?>
</label>
<input class="widefat"
id="<?php echo esc_attr($this->get_field_id('title')); ?>"
name="<?php echo esc_attr($this->get_field_name('title')); ?>"
type="text"
value="<?php echo esc_attr($title); ?>">
</p>
<?php
}
/**
* 更新小工具设置
*/
public function update($new_instance, $old_instance) {
$instance = array();
$instance['title'] = (!empty($new_instance['title'])) ?
sanitize_text_field($new_instance['title']) :
'';
return $instance;
}
}
// 注册小工具
add_action('widgets_init', function() {
register_widget('FSC_Language_Switcher_Widget');
});
// 处理语言切换请求
add_action('init', 'fsc_handle_language_switch');
function fsc_handle_language_switch() {
if (isset($_GET['fsc_lang']) && !empty($_GET['fsc_lang'])) {
$lang_code = sanitize_text_field($_GET['fsc_lang']);
// 验证语言代码是否有效
$valid_languages = array('en_US', 'zh_CN', 'fr_FR', 'de_DE', 'es_ES', 'ja_JP');
if (in_array($lang_code, $valid_languages)) {
// 设置cookie保存语言偏好(30天有效期)
setcookie('fsc_preferred_language', $lang_code, time() + (30 * DAY_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN);
// 设置会话变量
$_SESSION['fsc_current_language'] = $lang_code;
// 过滤locale
add_filter('locale', function($locale) use ($lang_code) {
return $lang_code;
});
}
}
}
?>
自动化翻译集成
1. 集成机器翻译API
<?php
/**
* 机器翻译服务集成
*/
class FSC_Machine_Translation {
private $api_key;
private $service;
public function __construct($api_key = '', $service = 'google') {
$this->api_key = $api_key;
$this->service = $service;
}
/**
* 翻译文本
* @param string $text 要翻译的文本
* @param string $target_lang 目标语言
* @param string $source_lang 源语言
* @return string 翻译结果
*/
public function translate_text($text, $target_lang, $source_lang = 'en') {
// 检查缓存
$cache_key = 'fsc_translation_' . md5($text . $target_lang . $source_lang);
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached;
}
$translated = '';
switch ($this->service) {
case 'google':
$translated = $this->translate_google($text, $target_lang, $source_lang);
break;
case 'deepl':
$translated = $this->translate_deepl($text, $target_lang, $source_lang);
break;
case 'microsoft':
$translated = $this->translate_microsoft($text, $target_lang, $source_lang);
break;
}
// 缓存结果(24小时)
if (!empty($translated)) {
set_transient($cache_key, $translated, DAY_IN_SECONDS);
}
return $translated;
}
/**
* Google翻译API
*/
private function translate_google($text, $target_lang, $source_lang) {
$url = 'https://translation.googleapis.com/language/translate/v2';
$args = array(
'key' => $this->api_key,
'q' => $text,
'target' => $this->map_language_code($target_lang, 'google'),
'source' => $this->map_language_code($source_lang, 'google'),
'format' => 'text'
);
$response = wp_remote_post($url, array(
'body' => $args,
'timeout' => 15
));
if (is_wp_error($response)) {
error_log('Google翻译API错误: ' . $response->get_error_message());
return $text; // 返回原文
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['data']['translations'][0]['translatedText'])) {
return $body['data']['translations'][0]['translatedText'];
}
return $text;
}
/**
* 语言代码映射
*/
private function map_language_code($wp_locale, $service) {
$mapping = array(
'google' => array(
'en_US' => 'en',
'zh_CN' => 'zh-CN',
'fr_FR' => 'fr',
'de_DE' => 'de',
'es_ES' => 'es',
'ja_JP' => 'ja'
),
'deepl' => array(
'en_US' => 'EN',
'zh_CN' => 'ZH',
'fr_FR' => 'FR',
'de_DE' => 'DE',
'es_ES' => 'ES',
'ja_JP' => 'JA'
)
);
return isset($mapping[$service][$wp_locale]) ?
$mapping[$service][$wp_locale] :
substr($wp_locale, 0, 2);
}
/**
* 批量翻译产品信息
*/
public function batch_translate_products($product_ids, $target_lang) {
$results = array();
foreach ($product_ids as $product_id) {
$product_data = array(
'name' => get_post_meta($product_id, 'product_name', true),
'description' => get_post_meta($product_id, 'product_description', true),
'specifications' => get_post_meta($product_id, 'product_specifications', true)
);
$translated_data = array();
foreach ($product_data as $field => $content) {
if (!empty($content)) {
$translated_data[$field] = $this->translate_text(
$content,
$target_lang,
'en'
);
}
}
// 保存翻译
FSC_Product_Translator::save_product_translations(
$product_id,
array_keys($translated_data),
array($target_lang => $translated_data)
);
$results[$product_id] = $translated_data;
}
return $results;
}
}
?>
测试与调试
1. 创建测试工具
<?php
/**
* 多语言支持测试工具
*/
class FSC_Localization_Test {
/**
* 运行完整性测试
*/
public static function run_integrity_tests() {
$tests = array();
// 测试1: 检查语言文件是否存在
$tests['language_files'] = self::test_language_files();
// 测试2: 检查翻译函数使用
$tests['translation_functions'] = self::test_translation_functions();
// 测试3: 测试日期本地化
$tests['date_localization'] = self::test_date_localization();
// 测试4: 测试货币本地化
$tests['currency_localization'] = self::test_currency_localization();
// 测试5: 测试动态内容翻译
$tests['dynamic_content'] = self::test_dynamic_content_translation();
return $tests;
}
/**
* 测试语言文件
*/
private static function test_language_files() {
$plugin_dir = plugin_dir_path(__FILE__);
$language_dir = $plugin_dir . 'languages/';
$required_files = array(
'flexible-supply-chain.pot',
'flexible-supply-chain-en_US.mo',
'flexible-supply-chain-zh_CN.mo'
);
$results = array();
foreach ($required_files as $file) {
$file_path = $language_dir . $file;
$results[$file] = array(
'exists' => file_exists($file_path),
'path' => $file_path,
'size' => file_exists($file_path) ? filesize($file_path) : 0
);
}
return $results;
}
/**
* 测试翻译覆盖率
*/
public static function test_translation_coverage() {
// 扫描插件目录,查找所有翻译字符串
$plugin_files = self::scan_plugin_files();
$translation_strings = array();
$total_strings = 0;
$translated_strings = 0;
foreach ($plugin_files as $file) {
$content = file_get_contents($file);
// 查找所有翻译函数调用
preg_match_all(
'/__(.*?)['"]s*,s*['"]flexible-supply-chain['"]/',
$content,
$matches
);
if (!empty($matches[1])) {
foreach ($matches[1] as $string) {
$total_strings++;
$string = trim($string, ''"');
// 检查这个字符串是否有翻译
$translated = __($string, 'flexible-supply-chain');
if ($translated !== $string) {
$translated_strings++;
}
$translation_strings[] = array(
'string' => $string,
'translated' => $translated !== $string,
'translation' => $translated,
'file' => basename($file)
);
}
}
}
$coverage = $total_strings > 0 ?
($translated_strings / $total_strings) * 100 :
0;
return array(
'total_strings' => $total_strings,
'translated_strings' => $translated_strings,
'coverage_percentage' => round($coverage, 2),
'strings' => $translation_strings
);
}
/**
* 扫描插件文件
*/
private static function scan_plugin_files($directory = null) {
if ($directory === null) {
$directory = plugin_dir_path(__FILE__);
}
$files = array();
$excluded = array('node_modules', 'vendor', '.git', 'tests');
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$path = $file->getPathname();
$exclude = false;
foreach ($excluded as $exclude_dir) {
if (strpos($path, $exclude_dir) !== false) {
$exclude = true;
break;
}
}
if (!$exclude) {
$files[] = $path;
}
}
}
return $files;
}
/**
* 生成翻译报告
*/
public static function generate_translation_report() {
$tests = self::run_integrity_tests();
$coverage = self::test_translation_coverage();
$report = array(
'generated_at' => current_time('mysql'),
'plugin_version' => FSC_VERSION,
'wordpress_locale' => get_locale(),
'tests' => $tests,
'coverage' => $coverage,
'recommendations' => array()
);
// 生成建议
if ($coverage['coverage_percentage'] < 90) {
$report['recommendations'][] = sprintf(
'翻译覆盖率较低(%.1f%%),建议补充翻译缺失的字符串',
$coverage['coverage_percentage']
);
}
// 检查缺失的语言文件
foreach ($tests['language_files'] as $file => $info) {
if (!$info['exists']) {
$report['recommendations'][] = "缺少必要的语言文件: {$file}";
}
}
return $report;
}
}
?>
最佳实践与优化建议
1. 性能优化策略
<?php
/**
* 多语言性能优化
*/
class FSC_Localization_Optimizer {
/**
* 初始化优化
*/
public static function init_optimizations() {
// 启用翻译缓存
add_action('init', array(__CLASS__, 'enable_translation_cache'));
// 预加载常用翻译
add_action('wp_loaded', array(__CLASS__, 'preload_translations'));
// 优化数据库查询
add_filter('query', array(__CLASS__, 'optimize_translation_queries'));
}
/**
* 启用翻译缓存
*/
public static function enable_translation_cache() {
if (!defined('WP_CACHE')) {
define('WP_CACHE', true);
}
// 使用对象缓存存储翻译
if (wp_using_ext_object_cache()) {
add_filter('override_load_textdomain',
array(__CLASS__, 'cache_textdomain'), 10, 3);
}
}
/**
* 缓存文本域
*/
public static function cache_textdomain($override, $domain, $mofile) {
$cache_key = 'textdomain_' . $domain . '_' . md5($mofile);
$cached = wp_cache_get($cache_key, 'translations');
if ($cached !== false) {
global $l10n;
if (isset($l10n[$domain])) {
return true;
}
}
// 如果没有缓存,正常加载并缓存
$loaded = load_textdomain($domain, $mofile);
if ($loaded) {
wp_cache_set($cache_key, true, 'translations', HOUR_IN_SECONDS);
}
return $override;
}
/**
* 预加载常用翻译
*/
public static function preload_translations() {
$preload_strings = array(
'Order',
'Product',
'Supplier',
'Inventory',
'Shipping',
'Status',
'Price',
'Quantity',
'Total',
'Date'
);
foreach ($preload_strings as $string) {
// 预加载到内存
__($string, 'flexible-supply-chain');
}
}
/**
* 懒加载翻译
*/
public static function lazy_load_translation($text, $domain) {
static $loaded_domains = array();
if (!isset($loaded_domains[$domain])) {
// 延迟加载文本域
if (!is_textdomain_loaded($domain)) {
load_textdomain($domain,
WP_LANG_DIR . "/plugins/{$domain}-" . get_locale() . '.mo');
}
$loaded_domains[$domain] = true;
}
return __($text, $domain);
}
}
?>
2. SEO优化
<?php
/**
* 多语言SEO优化
*/
class FSC_Multilingual_SEO {
/**
* 添加hreflang标签
*/
public static function add_hreflang_tags() {
if (!is_singular('fsc_product')) {
return;
}
$languages = apply_filters('fsc_available_languages', array(
'en_US' => 'en',
'zh_CN' => 'zh-hans',
'fr_FR' => 'fr',
'de_DE' => 'de',
'es_ES' => 'es'
));
$current_id = get_the_ID();
$current_url = get_permalink();
foreach ($languages as $locale => $lang_code) {
// 获取其他语言版本的URL
$translated_url = self::get_translated_url($current_id, $locale);
if ($translated_url) {
echo sprintf(
'<link rel="alternate" hreflang="%s" href="%s" />' . "n",
esc_attr($lang_code),
esc_url($translated_url)
);
}
}
// 添加x-default
echo sprintf(
'<link rel="alternate" hreflang="x-default" href="%s" />' . "n",
esc_url($current_url)
);
}
/**
* 获取翻译后的URL
*/
private static function get_translated_url($post_id, $locale) {
// 这里应该根据您的URL结构实现
// 示例:添加语言参数或使用子目录
$base_url = get_permalink($post_id);
if ($locale === 'en_US') {
return $base_url;
}
return add_query_arg('lang', $locale, $base_url);
}
/**
