【问题标题】:How to change the language of the email dynamically according to user's language in WordPress?如何在WordPress中根据用户的语言动态更改电子邮件的语言?
【发布时间】:2021-03-10 22:03:07
【问题描述】:

我正在寻找一种方法,通过定制插件使用wp_mail() 函数根据用户的语言发送简单的 WordPress 电子邮件。通过设置切换 WordPress 语言后,我可以翻译电子邮件并以正确的语言接收电子邮件。但是如何根据用户的语言动态改变邮件的语言呢?

我已经保存了用户的首选语言列表。主题和电子邮件内容被翻译成不同的语言。出于测试目的,我一直在尝试强制使用语言环境,但它似乎没有做任何事情,并且电子邮件仍以默认的 WordPress en_US 语言环境到达。

$locale = 'es_ES';
switch_to_locale($locale);
$to      = 'test@email.com';
$subject = __('Email subject', 'textdomain');
$message = __('My email content', 'textdomain');

wp_mail( $to, $subject, $message, $headers );
restore_previous_locale();

如果能收到一些反馈、经验或知识,我将非常感激如何简单地切换某些字符串的语言环境,然后将其恢复为原始状态?

【问题讨论】:

    标签: wordpress email locale translate


    【解决方案1】:

    看来我终于搞定了。

    1. 首先 - 确保您已准备好带有适当翻译的 .mo 翻译文件
    2. 在调用switch_to_locale($locale); 之后,您还必须加载文本域。我使用了load_plugin_textdomain() 函数。

    如果有人遇到此线程,这是更新的代码:

    $locale = 'es_ES';
    switch_to_locale($locale);
    load_plugin_textdomain('textdomain', false, basename( plugin_dir_path( __DIR__ ) ) . '/languages');
    $to      = 'test@email.com';
    $subject = __('Email subject', 'textdomain');
    $message = __('My email content', 'textdomain');
    
    wp_mail( $to, $subject, $message, $headers );
    restore_previous_locale();
    

    【讨论】:

      猜你喜欢
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多