Hoàng Anh
Hoàng Anh

Reputation: 11

How to add php to javascript google tag

Please help me check this js, i want to add .php in javascript for gtag js, but my code fails. This is the google tag:

<script>gtag('event', 'page_view', {
'send_to': 'AW-xxx',
'ecomm_pagetype': 'replace with value',
'ecomm_prodid': 'replace with value',
'ecomm_totalvalue': 'replace with value' });</script>

And here is my code:

<script>
      gtag('event', 'page_view', {
        'send_to': 'AW-xxx',
        'ecomm_prodid': ' . json_encode( $this->mc_prefix . ( 0 == $this->product_identifier ? get_the_ID() : $product->get_sku() ) ) . ',
        'ecomm_pagetype': \'product\',
        'ecomm_totalvalue': ' . $product->get_price() . '
    };
</script>

I use WooCommerce AdWords Dynamic Remarketing plugin.


This is my code, please check at line 455

My Full Code

Upvotes: 0

Views: 257

Answers (1)

Gary Thomas
Gary Thomas

Reputation: 2331

You need to open and close the PHP tag in order to use PHP functions and variables, like so:

<script>
    gtag('event', 'page_view', {
        'send_to': 'AW-xxx',
        'ecomm_prodid': '<?php echo json_encode( $this->mc_prefix . ( 0 == $this->product_identifier ? get_the_ID() : $product->get_sku() ) ); ?>',
        'ecomm_pagetype': 'product',
        'ecomm_totalvalue': '<?php echo $product->get_price(); ?>'
    };
</script>

Edit:

So the above is actually invalid since the script is being created inside a PHP variable. Replace lines 455 to 463 of your gist with the following:

$product_id_code = '
    <script>
        gtag("event", "page_view", {
            "send_to": "'.json_encode($this->conversion_id, JSON_NUMERIC_CHECK ).'",
            "ecomm_prodid": "'.json_encode($this->mc_prefix.(0 == $this->product_identifier ? get_the_ID() : $product->get_sku())).'",
            "ecomm_pagetype": "product",
            "ecomm_totalvalue": "'.$product->get_price().'"
        });
    </script>
';

Upvotes: 1

Related Questions