Add Facebook Pixel Purchase Event Code to WooCommerce purchase completion page

771 Views Asked by At

I need to add the following to the purchase completion page in WooCommerce:

Copy the event code snippet. You can add parameters to send additional on-page data. fbq('track', 'Purchase');

I tried adding the following code to the child theme functions.php file:

add_action('wp_enqueue_scripts', 'qg_enqueue');
function qg_enqueue() {
    if (is_order_received_page()) {
        wp_enqueue_script(
            fbq('track', 'Purchase');
        );
    }
}

Fatal error. I'm sure I'm messing something up but I'm a little lost. I tried quite a bit of searching. I'm trying to add the script only to the order received page, WooCommerce Checkout endpoint. What's wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

There are missing quotes in your code inside wp_enqueue_script() function, so try to replace fbq('track', 'Purchase'); with "fbq('track', 'Purchase');", it should solve the error.

Now you should better use wc_enqueue_js() function using template_redirect hook as follows:

add_action('template_redirect', 'enqueue_fbq_purchase_event');
function enqueue_fbq_purchase_event() {
    if ( is_order_received_page() ) {
        wc_enqueue_js( "fbq('track', 'Purchase');" );
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should better work.