Search code examples
phpwordpressif-statementgoogle-ad-manager

WordPress: Echo Javascript for Google Ads Conversion Page


I'm trying to add some Javascript coming from Google for Ad Conversions on the thank you page. So this script should only appear on one page. Trying to use an if statement in PHP to echo the code but running into errors. This is what I currently have (with the Google ID replaced with something generic):

<?php if ( is_page( 'thankyou' )) {
    echo '<script>';
    echo 'gtag('event', 'conversion', {'send_to': 'AW-12345678901234567890123456'});'
    echo '</script>';
?>

The first and third echo's are fine but the middle one is not. What might be the proper fix?


Solution

  • Your second echo line breaks your string.


    You have 2 options to fix this:

    1. Change the inner quotes to double quotes

    echo 'gtag("event", "conversion", {"send_to": "AW-12345678901234567890123456"});';
    

    2. Break out of the quotes.

    You can use back slashes to not break out of your main string.

    echo 'gtag(\'event\', \'conversion\', {\'send_to\': \'AW-12345678901234567890123456\'});';
    

    I have also noticed on the second echo you were missing a semi colon.

    Source: PHP-Strings