Search code examples
phpwordpresswoocommercecustomization

Add tracking code to WooCommerce Thank You page for a specific product


Is there a way to customize this code to include an "If" statement to pull in a specific product ID so the tracking script is only added to the thank you page for that product? Something like this:

/* Add tracking code to thank you page for Product ID 27490 */
add_action( 'woocommerce_thankyou', 'my_custom_tracking' );

function my_custom_tracking( $order_id ) {

    // Lets grab the order
    $order = wc_get_order( $order_id );
    
    // This is the order total
    //$order->get_total();
 
    // This is how to grab line items from the order 
    $line_items = $order->get_items();

    // This loops over line items
    foreach ( $line_items as $item ) {
        // This will be a product
        //$product = $order->get_product_from_item( $item );
        $product_id = $item->get_product_id();
        if ( $product_id = "27490" ){  
            echo "<!-- Event snippet for Purchase Thank You Page for product 27490 -->
<script>
  gtag('event', 'conversion', {
      'send_to': 'XXXXXX',
      'value': 1.0,
      'currency': 'USD',
      'transaction_id': ''
  });
</script>";
        }
    }
}

Solution

  • Here's a clean solution to your question, this also puts the script in the footer, by passing your script to the footer_script enqueue.

    You could also hook replace the entire sub-function add_action( 'wp_print_footer_scripts',

    With wp_add_inline_script( 'your-enqueued-script-handle', $script ) which would be cleaner.

    add_action( 'woocommerce_thankyou', 'my_custom_tracking' );
    
    function my_custom_tracking( $order_id ) {
        
        // Lets grab the order.
        $order = wc_get_order( $order_id );
        
        // This is how to grab line items from the order.
        $line_items = $order->get_items();
        
        // This loops over line items.
        foreach ( $line_items as $item ) {
            if ( 27490 === $item->get_product_id() ) {
                $script = "gtag('event', 'conversion', {
                              'send_to': 'XXXXXX',
                              'value': 1.0,
                              'currency': 'USD',
                              'transaction_id': ''
                          });";
                add_action(
                    'wp_print_footer_scripts',
                    function() use ( $script ) {
                        echo '<!-- Event snippet for Purchase Thank You Page for product 27490 -->
                            <script>' . wp_kses_post( $script ) . '</script>';
                    }
                ); // end of add_action to footer script.
            }
        }
    }