一些主题和插件使用 urlencoded 简码。例如,WPBakery Page Builder 的 Progress Bar、Round Chart 或 Line Chart 等模块就是这种情况。在本指南中,我们将说明如何启用对此类简码所用内容的翻译。
什么是“urlencoded”简码?
当您插入使用 urlencoded 简码的元素,并将 WordPress 编辑器切换到文本模式时,您会看到它们类似于以下内容。
[vc_progress_bar values="%5B%7B%22label%22%3A%22Development%20Test%22%2C%22value%22%3A%2290%22%7D%2C%7B%22label%22%3A%22Design%20Test%22%2C%22value%22%3A%2280%22%7D%2C%7B%22label%22%3A%22Marketing%22%2C%22value%22%3A%2270%22%2C%22color%22%3A%22bar_blue%22%7D%5D" title="Progress Bar Title Test" units="%"]
此类简码中的 value 会被解码为类似于以下内容的 JSON 编码数组:
[{"label":"Development Test","value":"90"},{"label":"Design Test","value":"80"},{"label":"Marketing","value":"70","color":"bar_blue"}]最后,该 JSON 输出也会被解码为类似于以下内容的数组:
解码后的 JSON 数组
array (
0 =>
array (
'label' => 'Development Test',
'value' => '90',
),
1 =>
array (
'label' => 'Design Test',
'value' => '80',
),
2 =>
array (
'label' => 'Marketing',
'value' => '70',
'color' => 'bar_blue',
),
)如果您觉得这太复杂,请不要担心。这是一个内部过程,作为用户,您无需干预。
翻译“urlencoded”简码中的值
现在,让我们看看如何翻译该数组的 label 和 value 部分。在 WPML 3.9 版本之前,翻译此类简码很困难,但现在只需几个简单的步骤即可完成。
1. 将简码添加到您的 wpml-config.xml 文件中。
如果您没有该文件或对此不熟悉,此文档页面应该会有所帮助,尤其是页面构建器内容部分。
在您的 wpml-config.xml 中,除了为简码添加的常规代码外,您还需要添加 type="area" 和 encoding="urlencoded_json" 属性:
Progress bar 简码
<shortcode>
<tag>vc_progress_bar</tag>
<attributes>
<attribute encoding="allow_html_tags">title</attribute>
<attribute type="area" encoding="urlencoded_json">values</attribute>
</attributes>
</shortcode>2. 将以下代码添加到您主题的 functions.php 文件中。
Progress bar 函数
add_filter( 'wpml_pb_shortcode_encode', 'wpml_pb_shortcode_encode_urlencoded_json', 10, 3 );
function wpml_pb_shortcode_encode_urlencoded_json( $string, $encoding, $original_string ) {
if ( 'urlencoded_json' === $encoding ) {
$output = array();
foreach ( $original_string as $combined_key => $value ) {
$parts = explode( '_', $combined_key );
$i = array_pop( $parts );
$key = implode( '_', $parts );
$output[ $i ][ $key ] = $value;
}
$string = urlencode( json_encode( $output ) );
}
return $string;
}
add_filter( 'wpml_pb_shortcode_decode', 'wpml_pb_shortcode_decode_urlencoded_json', 10, 3 );
function wpml_pb_shortcode_decode_urlencoded_json( $string, $encoding, $original_string ) {
if ( 'urlencoded_json' === $encoding ) {
$rows = json_decode( urldecode( $original_string ), true );
$string = array();
foreach ( $rows as $i => $row ) {
foreach ( $row as $key => $value ) {
if ( in_array( $key, array( 'text', 'title', 'features', 'substring', 'btn_text', 'label', 'value', 'y_values' ) ) ) {
$string[ $key . '_' . $i ] = array( 'value' => $value, 'translate' => true );
} else {
$string[ $key . '_' . $i ] = array( 'value' => $value, 'translate' => false );
}
}
}
}
return $string;
}上述代码中最重要的部分位于以下行:
if ( in_array( $key, array( 'text', 'title', 'features', 'substring', 'btn_text', 'label', 'value', 'y_values' ) ) )
在这里,您必须添加可以从解码后的 JSON 数组中获取的正确键。在我们的示例中,它们将是 label 和 value。
就是这样!现在,在翻译编辑器中,您将看到这些简码的 label 和 value 字段,它们已准备好进行翻译。

翻译编辑器:可供翻译的“label”和“value”