How to insert Google Merchant Review JS code in Wo

2019-01-27 12:17发布

问题:

I want to complete the variables the Google Merchant Review codes asks to be completed on the checkout page:

<script src="https://apis.google.com/js/platform.js?onload=renderOptIn" async defer></script>

<script>
  window.renderOptIn = function() {
    window.gapi.load('surveyoptin', function() {
      window.gapi.surveyoptin.render(
        {
          "merchant_id": mymerchantid,
          "order_id": "ORDER_ID",
          "email": "CUSTOMER_EMAIL",
          "delivery_country": "COUNTRY_CODE",
          "estimated_delivery_date": "YYYY-MM-DD"
        });
    });
  }
</script>

I need to echo the following variables:

ORDER_ID: ID number of the WooCommerce order ID

CUSTOMER_EMAIL: The email listed in the customer information section of the order

DELIVERY_COUNTRY: I think I can just fill it with ES since I only sell in Spain

ESTIMATED_DELIVERY_DATE: I already have a function I use to calculate the shipping date, so I guess I can use that php function here.

In conclusion, I would need help figuring out how do I echo the ORDER_ID and CUSTOMER_EMAIL in the checkout page, concretely inside of said script. I'm kind of clueless on how to do so, since all I tried had kind of a catastrophic result

Thank you very much for reading!

TL;DR: How do I get to echo the ORDER_ID and CUSTOMER_EMAIL in the after payment checkout page on WooCommerce?

回答1:

If you want to add a JavaScript goal conversions code to your Order complete or Thankyou page then you have to use woocommerce_thankyou hook.

Here is the code:

function wh_CustomReadOrder($order_id) {
    //getting order object
    $order = wc_get_order($order_id);
    $email = $order->billing_email;
    ?>
    <script src="https://apis.google.com/js/platform.js?onload=renderOptIn" async defer></script>
    <script>
        window.renderOptIn = function () {
            window.gapi.load('surveyoptin', function () {
                window.gapi.surveyoptin.render(
                        {
                            "merchant_id": mymerchantid,
                            "order_id": "<?php echo $order_id; ?>",
                            "email": "<?php echo $email; ?>",
                            "delivery_country": "COUNTRY_CODE",
                            "estimated_delivery_date": "YYYY-MM-DD"
                        }
                );
            });
        };
    </script>
    <?php
}

add_action('woocommerce_thankyou', 'wh_CustomReadOrder');

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.
Code is tested and works.

Reference:

  • Official Doc

Related Questions

  • Woocommerce Get Orders on Thank you page and pass data javascript snippet
  • Woocommerce: Checking if successful purchase was from a new or returning customer

Hope this helps!