wordpress - 在特定页面上加载脚本

时间:2018-01-09 09:05:58

标签: javascript php wordpress

我是wordpress的新手,我的国家/地区的城市页面为“www.mysite.it/city”。

现在我想为每个城市加载一个google analitycs脚本,我试试这样:

的header.php

if(is_page('city_1'))
    $img_src = 'city_1_image.jpg';
    $city_id_google = 'UA-97242948-24';

if(is_page('city_2'))
    $img_src = 'city_2_image.jpg';
    $city_id_google = 'UA-97242948-7';  
....

<!DOCTYPE html>
<html>
<head>
...

</head>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $city_id_google ?>"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '<?php echo $city_id_google ?>');
</script>

像这样我总是在所有页面上看到我加载的第一个“$ city_id_google”,也许是缓存wordpress?也许我可以用JS做得更好吗?

感谢您的支持!

1 个答案:

答案 0 :(得分:0)

您最好使用wordpress custom fields

// This will be the default value and will use if there's no custom field value
$city_id_google = 'UA-97242948-7';

// get the UA from custom field value
$city_id_google_from_meta = get_post_meta( get_the_ID(), 'the_meta_key_you_assign', true);

// Override $city_id_google if custom field has value
if ( $city_id_google_from_meta  ) $city_id_google = $city_id_google_from_meta;

或者仅在存在自定义字段元值

时才加载脚本
//get post meta value
$city_id_google_from_meta = get_post_meta( get_the_ID(), 'the_meta_key_you_assign', true);

// check if meta key has value 
if ( $city_id_google_from_meta  ) { ?>
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $city_id_google_from_meta ?>"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', '<?php echo $city_id_google_from_meta; ?>');
    </script>
<?php }

如果您想在特定的

上运行某些内容,请检查Conditional Tags