使用__()和sprintf()转换WP


Translating WP with __() and sprintf()

我正在尝试翻译WP主题。我有这个代码:

$translation = __( get_color(), 'textdomain' );

它很有效,我从get_color()函数中动态地获取颜色,并且它转换得很好。但当我使用"主题检查"插件时,我会收到这个代码的错误。

我需要使用这个替代:

$translation = sprintf( __( '%s', 'textdomain' ), get_color() );

但在这种情况下,我的占位符%s不会翻译,我得到了原始颜色名称(未翻译)。

我做错了什么?非常感谢。

echo sprintf(__("text %s", 'your__text_domain'), $data);

我很惊讶没有人提到"翻译人员";注释,即告诉翻译器sprintf中的每个变量是什么。示例:

sprintf(
    /* translators: %s: Name of a city */
    esc_html__( 'Your city is %s.', 'my-plugin' ),
    esc_html( $city )
);
sprintf(
     /* translators: 1: Name of a city 2: ZIP code */
    esc_html__( 'Your city is %1$s, and your zip code is %2$s.', 'my-plugin' ),
    esc_html( $city ),
    esc_html( $zipcode )
);

我们用esc_html__对转换进行转义,以保护来自社区翻译字符串的XSS,并用esc_html对变量$city中的XSS进行动态输出转义。

请参阅:https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/#variables

A。,

在您的代码中:

$translation = sprintf( __( '%s', 'textdomain' ), get_color() );

CCD_ 5函数检查字符串"%s"的翻译(可能没有翻译),然后用CCD_ 6的结果替换"%s"。因此get_color()的值永远不会通过转换函数。

我不确定这里的正确解决方案是什么,也许在这种情况下忘记主题检查吧。

许多提取可翻译字符串的翻译工具都会查找字符串文本,如下所示:

$translation = __( 'red', 'textdomain' );

可以肯定的是,主题检查插件会提醒您,此类工具不会提取动态字符串。这是因为在提取过程中不会执行代码,因此表达式get_color()不会被计算为可翻译的字符串。

如果您不关心与字符串提取工具的兼容性,那么只需按照第一个示例保留代码即可(第二个示例已经指出是错误的)。

如果您确实希望您的代码与翻译工具配合使用,那么我建议您创建一个PHP文件,其中包含所有可能的颜色值。(假设该列表是有限的)。你的文件看起来像这样:

<?php
__('red', 'textdomain' );
__('blue', 'textdomain' );
// and so on..

然后,如果你想阻止实际的翻译调用产生"主题检查"错误,你必须将其重构为不会被发现的东西。像这样的东西会被大多数提取器错过:

$translation = call_user_func( '__', get_color(), 'textdomain' );

*值得注意的是,主题检查的作者是WordPress的核心贡献者,并对正确使用WordPress i18n直言不讳。

在前两个回复中已经给出了答案。按照这个操作,但也不要忘记添加一个转义函数。

这就是如何翻译具有一个值或函数的文本:

sprintf(
    esc_html__( 'Your translatable text goes here and value is %s.', 'textdomain' ),
    $value_or_function
);

通过以下方式,您可以为可翻译文本添加多个值/函数

sprintf(
    esc_html__( 'this is how you can add multiple values. value1: %1$s, and value2: %2$s.', 'textdomain' ),
    $value_or_function1,
    $value_or_function2
);

下面是关于这个sprintf函数的简介:

arg1、arg2和++参数将以百分比(%)符号插入主字符串中。该功能"工作";"循序渐进";。在第一个%符号处插入arg1,在第二个%符号时插入arg2,依此类推。

语法:sprintf(format,arg1,arg2,arg++)

可能的格式值:

%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number (negative, zero or positive)
%e - Scientific notation using a lowercase (e.g. 1.2e+2)
%E - Scientific notation using a uppercase (e.g. 1.2E+2)
%u - Unsigned decimal number (equal to or greater than zero)
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%g - shorter of %e and %f
%G - shorter of %E and %f
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)

但通常我们使用%s,并假设参数值将是一个字符串。