Yonder Mann
Yonder Mann

Reputation: 23

How to wrap <script> into if statement for wordpress <head>

I've been trying to implement a code provided by a wordpress plugin maker and I need a bit of help confirming if it works or not. The plugin in question is the PaidMembership Pro and it provides a possibility to hide ads for members. This is the snippet of code I should add to the template:

if ( function_exists( 'pmpro_displayAds' ) && pmpro_displayAds() ) {
    //insert ad code here
}

The ad code is a simply google adsense code:

<script data-ad-client="ca-pub-111111111111111" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

I have no idea how to do it right. I tried adding it like this to wordpress header.php but wordpress throws me an error.

<?php if ( function_exists( 'pmpro_displayAds' ) && pmpro_displayAds() ) {
<script data-ad-client="ca-pub-111111111111111" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
} ?>

I tried a couple of other variations too but didn't seem to work. Could someone help me out at least pointing me to a direction where I can look for answers? How the if should be wrapped or should it be at all? If I don't wrap it at all, it just shows up on the top of the frontend.

Thanks

Upvotes: 2

Views: 258

Answers (1)

mptr
mptr

Reputation: 124

You have mixed HTML and PHP code in your try. To make PHP generate the HTML you wish, you have to echo it:

<?php
if ( function_exists( 'pmpro_displayAds' ) && pmpro_displayAds() ) {
  echo('<script data-ad-client="ca-pub-111111111111111" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>');
}
?>

for more on this, see echo() in PHP-Manuals

All PHP-Code (e.g. wordpress-logic) has to be wrapped in <?php ?> in order to get executed by the webserver.

Upvotes: 1

Related Questions