Home » WooCommerce: Add Different Facebook Pixels to Different Pages

WooCommerce: Add Different Facebook Pixels to Different Pages

by Tutor Aspire

Last week a client who was about to carry a Facebook Advertising campaign asked me something pretty interesting. We already saw in the past how to add conversion tracking to the Thank-you page, however this time was slightly different.

My client’s FB consultant required a code for the whole site, another code for the Checkout page only (“user has initiated checkout”), and another one for the Thank-you page (“user has purchased”). So, here’s how I did it.

WooCommerce: add different Facebook Tracking codes to different pages
WooCommerce: add different Facebook Tracking codes to different pages

Thinking out loud: conditional logic

When you code in WooCommerce you always need to ask yourself a question: does your snippet need to run on every page of the website?

If the answer is no, you probably heard already of conditional logic (I covered WooCommerce conditional logic in a previous tutorial). And this case is no different.

We need a different Facebook tracking code for:

  1. the whole site, excluding checkout & thank you page
  2. the Checkout page only
  3. the Thank-you page only

So the trick is basically finding what’s the ideal PHP to execute something along the lines of: IF (CONDITION) > THEN (ECHO THIS).

If you took a look at my tutorial, the conditional tag to target the checkout page is: is_checkout(). Problem is, this targets the Thank-you page as well (they have the same page ID!). So I had to use another conditional tag, called is_wc_endpoint_url( ‘order-received’ ), which targets exclusively that “endpoint”.

Ok, let’s see how the PHP works 🙂

PHP snippet: Add Different Facebook Pixels to Different WooCommerce Pages

/**
 * @snippet       Add Different Facebook Pixels to Different WooCommerce Pages
 * @how-to        Get tutoraspire.com FREE
 * @sourcecode    https://tutoraspire.com/?p=21309
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 2.6.8
 */

add_action( 'wp_head', 'tutoraspire_head_conditional_fb_pixel' );

function tutoraspire_head_conditional_fb_pixel() {

if ( is_checkout() && !is_wc_endpoint_url( 'order-received' ) ) {

// FIRST WE TARGET THE CHECKOUT PAGE WITH is_checkout()
// AND WE MAKE SURE TO EXCLUDE THE THANK YOU PAGE

?>








  

You may also like