Adding a code to WordPress header based on local language into functions.php

耗尽温柔 提交于 2019-12-12 05:16:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!