我正在尝试使用WPML在wordpress的.JS文件中有条件地显示链接。我尝试过以下但现在正在努力;
var getLangCode = <?php echo '"' . ICL_LANGUAGE_CODE . '"' ; ?>; //WPML code to detect site's language. Getting error on this line
if (getLangCode === 'en-US') {
var imagesPath = 'https://website-domain.com/file-name.jpg';
}else if (getLangCode === 'fr-FR') {
var imagesPath = 'https://website-domain.com/fr/file-name.jpg';
}
我在上面的行Uncaught SyntaxError: Unexpected token <
上收到以下错误
我正在使用链接将图像和文本添加到容器中......文本工作正常,因为我使用wp_localize_script
制作字符串Translateable但是当我切换到法语时,图像不再显示,因为现在链接包含fr
任何帮助解决这个问题将非常感激
由于你已经在使用wp_localize_script,我不仅要使用它来传递翻译,还要传递你的语言代码,正如一些评论和教程中所述。像这样:
在WordPress中
wp_enqueue_script( 'some_handler', get_template_directory_uri() . '/js/your_javascript.js' );
$dataToBePassedtoJS = array(
'language_code' => ICL_LANGUAGE_CODE,
'translate_string' => __( 'Translate me!', 'default' )
);
wp_localize_script( 'some_handler', 'php_vars_for_js', $dataToBePassedtoJS );
// the 'php_vars_for_js' will be an object in JS,
// it's properties will be the content of the dataToBePassedtoJS array.
在你的JavaScript中
(function($) {
"use strict";
// get the ICL_LANGUAGE_CODE passed by wp_localize_script's 'php_vars_for_js' to your JS:
var getLangCode = php_vars_for_js.language_code;
// show it in the console, just for fun
console.log ('ICL_LANGUAGE_CODE passed from WordPress: ' + getLangCode);
// so now you have the getLangCode, you can use it for your conditional
if (getLangCode === 'en') {
var imagesPath = 'https://website-domain.com/file-name.jpg';
} else if (getLangCode === 'fr') {
var imagesPath = 'https://website-domain.com/fr/file-name.jpg';
}
}
}(jQuery));
这样,您可以从WordPress PHP中获取任何所需的变量以传递给您的JS。
尝试:1)删除此行:
var getLangCode = <?php echo '"' . ICL_LANGUAGE_CODE . '"' ; ?>; //WPML code to detect site's language. Getting error on this line
2)将此代码添加到您的functions.php
add_action('wp_head', 'change_this_name');
function change_this_name() {
?>
<script type="text/javascript">
var getLangCode = <?php echo '"' . ICL_LANGUAGE_CODE . '"' ; ?>; //WPML code to detect site's language. Getting error on this line
</script>
<?php
};