仅向 Facebook、Twitter 访问者显示 Google AdSense 广告

Displaying Google AdSense Advertisements only to Facebook, Twitter Visitors

我正在使用以下代码。当我将此代码放入 single.php 时,它会显示 内容为 的广告。我希望,当 Facebook 访问者访问我的 URL 时,它会显示 广告而不显示任何内容。当其他访问者正常访问URL时,应该显示内容。

<?php

    $ref = $_SERVER['HTTP_REFERER'];
    if (preg_match("(facebook)", $ref) != false) {
        echo <<<END
<script type="text/javascript"><!--
    google_ad_client = "xx-xx-xxxxxxxxxxxxxxxxxx";
    /* xxxxxxxx xxxxxx xxx xxx xxx xx xxxxxx */
    google_ad_slot = "xxxxxxxxxxxxxx";
    google_ad_width = xxx;
    google_ad_height = xxx;
    //-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
END;
    }
    else {
        echo "";
    }

?>

如果single.php放错了地方,我应该放在哪里呢?

请试一试:

<?php

    $ref = $_SERVER['HTTP_REFERER'];
    if (preg_match('facebook\.com', $ref) != false) {

?>
<script type="text/javascript"><!--
    google_ad_client = "xx-xx-xxxxxxxxxxxxxxxxxx";
    /* xxxxxxxx xxxxxx xxx xxx xxx xx xxxxxx */
    google_ad_slot = "xxxxxxxxxxxxxx";
    google_ad_width = xxx;
    google_ad_height = xxx;
    //-->
</script>
<script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<?php

    } else {
        echo "";
    }

?>

另一种检查引荐的方法是使用 strpos 而不是 preg_match

<?php

    $ref = $_SERVER['HTTP_REFERER'];
    if (strpos($ref, 'facebook.com') != false) {

?>
<script type="text/javascript"><!--
    google_ad_client = "xx-xx-xxxxxxxxxxxxxxxxxx";
    /* xxxxxxxx xxxxxx xxx xxx xxx xx xxxxxx */
    google_ad_slot = "xxxxxxxxxxxxxx";
    google_ad_width = xxx;
    google_ad_height = xxx;
    //-->
</script>
<script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<?php

    } else {
        echo "";
    }

?>