-2

So I am helping my friend with his woocommerce WordPress site. He has some short javascript code that needs to be added to the thank you page for the site.

The javascript code takes three variables (totalCost, orderId and setProductId). I can not get to the HTML. So how do I add this code to the PHP and also, how do I access the variables from the PHP and write them into the javascript?

And where in the already existing code should I add it? Is it in the functions.php file for the theme?

I would be super thankful for help!

EDIT:

So would this work?

   add_action( 'studentkortet_tracking', 'my_custom_tracking' );

function studentkortet_tracking($order_id){
?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo ($order->order_total - $order->order_shipping); ?>');
sale.setOrderID('<?php echo $order->id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php

}
Anton Kimfors
  • 31
  • 1
  • 2
  • 4
  • 1
    It seems to me that the php tags that wrap your js code block should be swapped around. Move `?>` to ` – mickmackusa Nov 06 '17 at 12:23
  • @mickmackusa do you think the edit above would work? – Anton Kimfors Nov 06 '17 at 13:28
  • Comments are a poor place to display code. Perhaps do a link to a pastebin or php sandbox etc. Then i can have a better look. I don't use wordpress. – mickmackusa Nov 06 '17 at 13:29
  • @mickmackusa is correct, you need to close the PHP tags before inserting your script tag, and then reopen PHP tag after closing the script tag. Your new edit looks like you've deleted the PHP tags from around the script block entirely which will not work. Review the example in my answer. – helgatheviking Nov 06 '17 at 13:29
  • Okay, thank you for the avice @mickmackusa – Anton Kimfors Nov 06 '17 at 13:33
  • What I do not understand is where that $order_id comes from. I am not used to PHP but won't I need to pass in that as a parameter? – Anton Kimfors Nov 06 '17 at 13:37
  • It *is* passed as a parameter by the `woocommerce_thankyou` action hook so that it is available in the `function studentkortet_tracking($order_id)`. Please see my updated answer, which is now merged with your code. PS- As of WooCommerce 3.0 directly accessing object properties( ex: `$order->id` ) is going to throw a lot of warnings. You need to always use getters/setters now. – helgatheviking Nov 06 '17 at 16:05

3 Answers3

3

Here is some working code, answered here

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>
2

Here's the correct way of accessing PHP variables within a script. It utilises the function wp_localize_script() so that PHP variables are accessible in a script file. First include this file in your functions.php file

function example_enqueue_scripts() {
    if( is_checkout() ) {

        $args = array( 'total_cost' => 443, 'order_id' => 4567, 'set_product_id' => 123 );

        wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js' );
        wp_localize_script( 'checkout-script', 'checkout_script', $args );
        wp_enqueue_script( 'checkout-script' );

    }
}

add_action( 'wp_enqueue_scripts', 'example_enqueue_scripts' );

Then include this javascript in a file under your theme folder called checkout-script.js for example.

(function( $ ) {
    'use strict';
    $(function() {
        var totalCost = checkout_script.total_cost;
        var orderId = checkout_script.order_id;
        var setProductId = checkout_script.set_product_id;

        exampleFunction( totalCost, orderId, setProductId  );

        function exampleFunction( totalCost, orderId, setProductId ) {
            //Do something in here
            //alert(totalCost);
        }

    });

})( jQuery );
Andrew Schultz
  • 4,092
  • 2
  • 21
  • 44
0

I don't know what setProductId is meant to be as a variable, but the hook you are looking for is woocommerce_thankyou. The $order_id is passed by default, which you can then use to grab the order object. Pretty much all the info related to the order can be accessed through the setter/getter methods on the order object.

/**
 * Print Javascript on Thankyou page.
 * @param  int $order_id 
 */
function so_47117329_thankyou( $order_id ){
    $order = wc_get_order( $order_id ); ?>

    <script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
    </script>
    <script type="text/javascript">
    PostAffTracker.setAccountId(’xxxxxx’);
    var sale = PostAffTracker.createSale();
    sale.setTotalCost('<?php echo $order->get_total() - $order->get_shipping_
(); ?>');
    sale.setOrderID('<?php echo $order_id; ?>');
    sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
    PostAffTracker.register();
    </script>

<?php
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );

Editing to add an alternative for enqueuing the scripts as suggested by @Andrew-Schultz. Using the woocommerce_thankyou hook gets you easy access to the $order_id, which would otherwise need to be retrieved from the URL. You will still access the javascript variables as he's shown in his answer.

/**
 * Enqueue Javascript on Thankyou page.
 * @param  int $order_id 
 */
function so_47117329_thankyou( $order_id ){
    $order = wc_get_order( $order_id );

    $args = array( 
       'total_cost' => $order->get_total(), 
       'order_id' => $order_id, 
       'set_product_id' => 123 
     );

    wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js', array(), false, true ); // Last parameter loads script in footer
    wp_localize_script( 'checkout-script', 'checkout_script', $args );
    wp_enqueue_script( 'checkout-script' );


}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
helgatheviking
  • 25,596
  • 11
  • 95
  • 152
  • This is not a good way of including javascript you should always use the included WordPress core functions such as wp_enqueue_scripts – Andrew Schultz Nov 05 '17 at 02:42
  • Agree that `wp_enqueue_scripts` is preferred. I think this is probably OK for a custom script you are adding to your own site.. ie: you aren't likely to see conflicts from other plugins adding the same script. But I'll edit to add an alternative that is more a combination of our two answers. – helgatheviking Nov 05 '17 at 14:30
  • Thank you so much for all help guys. Could someone help me with the edit I posted? Feeling so lost... – Anton Kimfors Nov 06 '17 at 10:13
  • Friendly reminder that we aren't all guys. :) You're welcome! And it looks like someone already commented about your edit. Hope you get it sorted. – helgatheviking Nov 06 '17 at 13:27
  • Hi @helgatheviking, thank you so much for the help! It was not my intention to disrespect, or anyhting like that, by using "guys". I just use that word for "groups" by people, no matter gender. However, thank you so much for the help! I think it works now :D – Anton Kimfors Nov 06 '17 at 22:49
  • I got a new problem... Any idea why I would get this? call_user_func_array() expects parameter 1 to be a valid callback. function '’studentkort_tracking’' not found or invalid function name in /home/iconfash/beta2.iconfashionwear.se/wp-includes/class-wp-hook.php on line 298 – Anton Kimfors Nov 07 '17 at 09:15
  • @AntonKimfors I know it wasn't meant disrespectfully. :) It's just worth asking if there might be better phrases. I'm working on it too. And regarding your error, when you add a function to a hook, that function must exist. `add_action( 'some_hook', 'studentkort_tracking' );` is expecting a `studentkort_tracking()` function to be defined somewhere. – helgatheviking Nov 07 '17 at 13:55
  • @helgatheviking But did I not just define it? – Anton Kimfors Nov 07 '17 at 17:23
  • I mean, did I not define it when I just created it above? – Anton Kimfors Nov 07 '17 at 17:44