0

In my functions.php I'm creating a Woocommerce simple hook, in which I'm intending to use javascript:

function mysite_woocommerce_payment_complete( $order_id ) {
    $order = wc_get_order( $order_id );
    ?>
    HELLO
    <script>
    var a =2;
    </script>
<?php
}
add_action( 'woocommerce_payment_complete', 'mysite_woocommerce_payment_complete', 10, 1 );

As you can see, inside my function, I'm exiting PHP. But for some reason, everything I'm writing outside of PHP just logs in the console (INSTEAD of and not in addition to executing). In my console I can see

HeLLO
<script>
var a =2;
...

Why does this behaviour occur? And why can't I use javascript inside this hook function?

Thanks in advance

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • No because `woocommerce_payment_complete` is like a sever side hook (an event hook) that is used to update data or to trigger an email for example… – LoicTheAztec Sep 11 '19 at 17:15
  • So it's impossible to use javaScript inside of it? What hook would you use for when order is complete to use custom js? Thanks – sir-haver Sep 11 '19 at 17:20
  • Javascript code need to be displayed (or used) on a frontend or a backend browsed page, on client side (not server side). You should better try explain what is the real purpose, what are you really trying to do. – LoicTheAztec Sep 11 '19 at 18:52
  • Oh I see, what I'm trying to add is send a dataLayer to Google Tag Manager. Ideally I would use the thank-you hook, but that doesn't trigger at all, I think because of an external thank-you plugin that I'm using – sir-haver Sep 12 '19 at 03:37
  • It doesn't work with woocommerce_thankyou hook, because you are using a plugin that redirects the customer somewhere else. – LoicTheAztec Sep 12 '19 at 07:17
  • Thanks a lot LoicTheAztec that's what I thought so, so generally speaking if I want to use the thankyou hook, must I disable that plugin? – sir-haver Sep 12 '19 at 08:00
  • Yes… Try without it, you will see that it works, and that the hook is triggered. – LoicTheAztec Sep 12 '19 at 08:09

0 Answers0