问题
I have to add a Javascript code to a WordPress header based on the current language used by the website. We use WPML string translation. I want to write a function like this:
function add_customcode_header(){
?>
if(ICL_LANGUAGE_CODE == 'ru')
{
<script>
code 1
</script>
}
else
{
<script>
code 2
</script>
}
}
<?php
add_action('wp_head', 'add_customcode_header');
This function should place the script with code 1
contents if the website language parameter is set to 'ru' and IF the language parameter is any other, it should add the code 2
for other languages
The magic question is - will this function work properly?
UPDATE:
The proper solution that works:
function add_customcode_header(){
if(ICL_LANGUAGE_CODE == 'ru')
{
echo '<script>
code 1
</script>';
}
else
{
echo '<script>
code 2
</script>';
}
}
add_action('wp_head', 'add_customcode_header');
回答1:
Your overall idea should work fine, however, in the example you posted, there were some syntax errors.
function add_customcode_header(){
if(ICL_LANGUAGE_CODE == 'ru')
{
echo '<script>
code 1
</script>';
}
else
{
echo '<script>
code 2
</script>';
}
}
add_action('wp_head', 'add_customcode_header');
or
function add_customcode_header(){
if(ICL_LANGUAGE_CODE == 'ru')?>
<script>
code 1
</script>
<?php
else ?>
<script>
code 2
</script>
<?php
}
add_action('wp_head', 'add_customcode_header');
Should both be syntactically correct, and it really just matters what you're more comfortable with.
来源:https://stackoverflow.com/questions/43788386/adding-a-code-to-wordpress-header-based-on-local-language-into-functions-php