WordPress 的插件语言
由于某些原因,我需要在 WP 插件页面自定义 Locale,使插件的页面能够以用户选择的语言呈现,并且不影响 WordPress 的整体 Locale。
我们知道插件通过 API load_plugin_textdomain() 载入 Gettext mo 文件实现国际化,那么我们只要在载入 mo 之前 hook WordPress Locale 不就可以了?
粗略看了一下源码,发现其实很简单,WP 的 Locale 保存在全局变量 $locale 中,那么劫持它就好了。
以下是 fanfou-tools 的部分实现代码,非常简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | // {{{ fanfou_init /** * fanfou_init * * @access public * @return void */ function fanfou_init() { global $wpdb, $fanfou; $wpdb->fanfou = $wpdb->prefix . 'fanfou'; if (isset($_GET['activate']) and $_GET['activate'] == 'true') { $fanfou->install_table(); $fanfou->install_options(); } $fanfou->get_settings(); if (($fanfou->last_download + $fanfou->download_interval) < time()) { add_action('shutdown', 'fanfou_update_posts'); } if (is_admin()) { wp_enqueue_script('prototype'); } // Using our own locale $custom_locale = get_option('fanfou_locale'); if (!$custom_locale or $custom_locale == 'default') { $custom_locale = WPLANG; } $GLOBALS['locale'] = $custom_locale; load_plugin_textdomain('fanfou-tools', 'wp-content/plugins/fanfou-tools'); } add_action('init', 'fanfou_init'); // }}} |