WordPress Meta Pixel Event Tracking | Blue Frog Docs

WordPress Meta Pixel Event Tracking

Track WordPress interactions and WooCommerce conversions with Meta Pixel standard and custom events

WordPress Meta Pixel Event Tracking

Learn how to implement Meta Pixel (Facebook Pixel) events for WordPress-specific user interactions, form submissions, and WooCommerce e-commerce tracking.

Standard Events Overview

Meta provides standard events that should be used when possible for better optimization:

Key Standard Events for WordPress

  • PageView - Automatic page load tracking
  • ViewContent - Product/post detail views
  • Search - WordPress search usage
  • AddToCart - WooCommerce add-to-cart actions
  • InitiateCheckout - WooCommerce checkout started
  • Purchase - Order completed
  • Lead - Form submissions
  • CompleteRegistration - User registration

Basic Event Tracking

add_action('wp_footer', 'track_wordpress_search');
function track_wordpress_search() {
    if (!is_search()) {
        return;
    }

    $search_query = get_search_query();
    ?>
    <script>
        fbq('track', 'Search', {
            search_string: '<?php echo esc_js($search_query); ?>',
            content_category: 'search'
        });
    </script>
    <?php
}

Track Blog Post Views

add_action('wp_footer', 'track_blog_post_view');
function track_blog_post_view() {
    if (!is_single()) {
        return;
    }

    global $post;
    $categories = wp_get_post_categories($post->ID, array('fields' => 'names'));
    ?>
    <script>
        fbq('track', 'ViewContent', {
            content_name: '<?php echo esc_js($post->post_title); ?>',
            content_category: '<?php echo esc_js(implode(', ', $categories)); ?>',
            content_type: 'blog_post',
            content_ids: ['<?php echo $post->ID; ?>']
        });
    </script>
    <?php
}

Track Page Views by Type

add_action('wp_footer', 'track_page_by_type');
function track_page_by_type() {
    if (!is_page()) {
        return;
    }

    global $post;
    $page_type = 'standard';

    // Identify key pages
    if (is_page('contact')) {
        $page_type = 'contact';
    } elseif (is_page('about')) {
        $page_type = 'about';
    } elseif (is_page(array('services', 'pricing', 'products'))) {
        $page_type = 'commercial';
    }
    ?>
    <script>
        fbq('trackCustom', 'PageTypeView', {
            page_type: '<?php echo esc_js($page_type); ?>',
            page_name: '<?php echo esc_js($post->post_title); ?>'
        });
    </script>
    <?php
}

Form Tracking

Contact Form 7

add_action('wp_footer', 'track_cf7_submissions');
function track_cf7_submissions() {
    ?>
    <script>
        document.addEventListener('wpcf7mailsent', function(event) {
            fbq('track', 'Lead', {
                content_name: 'Contact Form 7',
                content_category: 'contact_form',
                form_id: event.detail.contactFormId
            });
        }, false);
    </script>
    <?php
}

Gravity Forms

add_action('gform_after_submission', 'track_gf_submission', 10, 2);
function track_gf_submission($entry, $form) {
    ?>
    <script>
        fbq('track', 'Lead', {
            content_name: '<?php echo esc_js($form['title']); ?>',
            content_category: 'gravity_form',
            form_id: '<?php echo $form['id']; ?>'
        });
    </script>
    <?php
}

WPForms

add_action('wp_footer', 'track_wpforms_submissions');
function track_wpforms_submissions() {
    ?>
    <script>
        jQuery(document).on('wpformsAjaxSubmitSuccess', function(event, data) {
            fbq('track', 'Lead', {
                content_name: 'WPForms Submission',
                content_category: 'wpforms',
                form_id: data.form_id
            });
        });
    </script>
    <?php
}

User Authentication Events

User Registration

add_action('user_register', 'track_user_registration');
function track_user_registration($user_id) {
    // Set cookie to fire event on next page load
    setcookie('user_registered', 'true', time() + 60, '/');
}

add_action('wp_footer', 'fire_registration_event');
function fire_registration_event() {
    if (isset($_COOKIE['user_registered'])) {
        setcookie('user_registered', '', time() - 3600, '/');
        ?>
        <script>
            fbq('track', 'CompleteRegistration', {
                content_name: 'WordPress User Registration',
                status: 'completed'
            });
        </script>
        <?php
    }
}

User Login

add_action('wp_login', 'track_user_login', 10, 2);
function track_user_login($user_login, $user) {
    setcookie('user_logged_in', 'true', time() + 60, '/');
}

add_action('wp_footer', 'fire_login_event');
function fire_login_event() {
    if (isset($_COOKIE['user_logged_in'])) {
        setcookie('user_logged_in', '', time() - 3600, '/');
        ?>
        <script>
            fbq('trackCustom', 'UserLogin', {
                login_method: 'wordpress'
            });
        </script>
        <?php
    }
}

WooCommerce Events

ViewContent - Product Pages

add_action('woocommerce_after_single_product', 'track_product_view');
function track_product_view() {
    global $product;

    $categories = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'names'));
    ?>
    <script>
        fbq('track', 'ViewContent', {
            content_name: '<?php echo esc_js($product->get_name()); ?>',
            content_ids: ['<?php echo esc_js($product->get_sku() ?: $product->get_id()); ?>'],
            content_type: 'product',
            content_category: '<?php echo esc_js(implode('/', $categories)); ?>',
            value: <?php echo $product->get_price(); ?>,
            currency: '<?php echo get_woocommerce_currency(); ?>'
        });
    </script>
    <?php
}

AddToCart

add_action('wp_footer', 'track_add_to_cart_event');
function track_add_to_cart_event() {
    if (!is_product()) {
        return;
    }

    global $product;
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('.single_add_to_cart_button').on('click', function() {
                const quantity = parseInt($('.qty').val() || 1);
                const price = parseFloat('<?php echo $product->get_price(); ?>');

                fbq('track', 'AddToCart', {
                    content_name: '<?php echo esc_js($product->get_name()); ?>',
                    content_ids: ['<?php echo esc_js($product->get_sku() ?: $product->get_id()); ?>'],
                    content_type: 'product',
                    value: price * quantity,
                    currency: '<?php echo get_woocommerce_currency(); ?>'
                });
            });
        });
    </script>
    <?php
}

AJAX Add to Cart (for archive/shop pages)

add_action('wp_footer', 'track_ajax_add_to_cart');
function track_ajax_add_to_cart() {
    if (!is_shop() && !is_product_category() && !is_product_tag()) {
        return;
    }
    ?>
    <script>
        jQuery(document).ready(function($) {
            $(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
                const productID = $button.data('product_id');
                const productName = $button.closest('.product').find('.woocommerce-loop-product__title').text();
                const productPrice = parseFloat($button.closest('.product').find('.price .amount').text().replace(/[^0-9.]/g, ''));

                fbq('track', 'AddToCart', {
                    content_name: productName,
                    content_ids: [productID],
                    content_type: 'product',
                    value: productPrice,
                    currency: '<?php echo get_woocommerce_currency(); ?>'
                });
            });
        });
    </script>
    <?php
}

InitiateCheckout

add_action('woocommerce_before_checkout_form', 'track_initiate_checkout');
function track_initiate_checkout() {
    $cart = WC()->cart;
    $content_ids = array();
    $contents = array();

    foreach ($cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
        $content_ids[] = $product->get_sku() ?: $product->get_id();
        $contents[] = array(
            'id' => $product->get_sku() ?: $product->get_id(),
            'quantity' => $cart_item['quantity'],
            'item_price' => $product->get_price()
        );
    }
    ?>
    <script>
        fbq('track', 'InitiateCheckout', {
            content_ids: <?php echo json_encode($content_ids); ?>,
            contents: <?php echo json_encode($contents); ?>,
            content_type: 'product',
            value: <?php echo $cart->get_total(''); ?>,
            currency: '<?php echo get_woocommerce_currency(); ?>',
            num_items: <?php echo $cart->get_cart_contents_count(); ?>
        });
    </script>
    <?php
}

AddPaymentInfo

add_action('woocommerce_review_order_before_payment', 'track_add_payment_info');
function track_add_payment_info() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('input[name="payment_method"]').on('change', function() {
                fbq('track', 'AddPaymentInfo', {
                    content_category: 'checkout',
                    payment_method: $(this).val(),
                    value: <?php echo WC()->cart->get_total(''); ?>,
                    currency: '<?php echo get_woocommerce_currency(); ?>'
                });
            });
        });
    </script>
    <?php
}

Purchase

add_action('woocommerce_thankyou', 'track_purchase_event');
function track_purchase_event($order_id) {
    if (!$order_id) {
        return;
    }

    // Prevent duplicate tracking
    $tracked = get_post_meta($order_id, '_fb_pixel_tracked', true);
    if ($tracked) {
        return;
    }

    $order = wc_get_order($order_id);
    $content_ids = array();
    $contents = array();

    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        $content_ids[] = $product->get_sku() ?: $product->get_id();
        $contents[] = array(
            'id' => $product->get_sku() ?: $product->get_id(),
            'quantity' => $item->get_quantity(),
            'item_price' => $item->get_total() / $item->get_quantity()
        );
    }

    // Generate event_id for deduplication with CAPI
    $event_id = 'wc_order_' . $order_id;
    ?>
    <script>
        fbq('track', 'Purchase', {
            content_ids: <?php echo json_encode($content_ids); ?>,
            contents: <?php echo json_encode($contents); ?>,
            content_type: 'product',
            value: <?php echo $order->get_total(); ?>,
            currency: '<?php echo $order->get_currency(); ?>',
            num_items: <?php echo count($order->get_items()); ?>
        }, {
            eventID: '<?php echo $event_id; ?>'
        });
    </script>
    <?php

    // Mark as tracked
    update_post_meta($order_id, '_fb_pixel_tracked', 'yes');
}

Custom Events

Track Button Clicks

add_action('wp_footer', 'track_custom_button_clicks');
function track_custom_button_clicks() {
    ?>
    <script>
        document.querySelectorAll('.cta-button, .wp-block-button__link').forEach(function(button) {
            button.addEventListener('click', function() {
                fbq('trackCustom', 'CTAClick', {
                    button_text: this.textContent.trim(),
                    button_url: this.href || 'no-url',
                    page_location: window.location.pathname
                });
            });
        });
    </script>
    <?php
}

Track Video Plays

add_action('wp_footer', 'track_video_engagement');
function track_video_engagement() {
    ?>
    <script>
        // Track HTML5 video plays
        document.querySelectorAll('video').forEach(function(video) {
            video.addEventListener('play', function() {
                fbq('trackCustom', 'VideoPlay', {
                    video_title: video.getAttribute('title') || 'Untitled Video',
                    video_url: video.currentSrc
                });
            });
        });

        // Track YouTube embedded videos (requires YouTube API)
        if (typeof YT !== 'undefined') {
            const players = document.querySelectorAll('.youtube-player');
            players.forEach(function(playerElement) {
                const player = new YT.Player(playerElement, {
                    events: {
                        'onStateChange': function(event) {
                            if (event.data === YT.PlayerState.PLAYING) {
                                fbq('trackCustom', 'VideoPlay', {
                                    video_title: player.getVideoData().title,
                                    video_platform: 'youtube'
                                });
                            }
                        }
                    }
                });
            });
        }
    </script>
    <?php
}

Track Downloads

add_action('wp_footer', 'track_file_downloads');
function track_file_downloads() {
    ?>
    <script>
        document.querySelectorAll('a').forEach(function(link) {
            const href = link.getAttribute('href');
            if (!href) return;

            const extensions = /\.(pdf|zip|docx?|xlsx?|pptx?|txt|csv|mp4|mp3)$/i;
            if (extensions.test(href)) {
                link.addEventListener('click', function() {
                    const fileName = href.split('/').pop();
                    const fileExtension = fileName.split('.').pop().toLowerCase();

                    fbq('trackCustom', 'FileDownload', {
                        file_name: fileName,
                        file_type: fileExtension,
                        download_url: href
                    });
                });
            }
        });
    </script>
    <?php
}

Track Scroll Depth

// Track when users scroll 75% down the page
let scrollTracked75 = false;
window.addEventListener('scroll', function() {
    const scrollPercent = (window.scrollY + window.innerHeight) / document.body.scrollHeight * 100;

    if (scrollPercent >= 75 && !scrollTracked75) {
        scrollTracked75 = true;
        fbq('trackCustom', 'ScrollDepth', {
            scroll_percentage: 75,
            page_url: window.location.pathname
        });
    }
});

Event Tracking via GTM

If using Google Tag Manager, push events to dataLayer and let GTM fire Meta Pixel:

add_action('wp_footer', 'push_wc_events_to_datalayer');
function push_wc_events_to_datalayer() {
    if (is_product()) {
        global $product;
        ?>
        <script>
            dataLayer.push({
                'event': 'productView',
                'productID': '<?php echo esc_js($product->get_sku() ?: $product->get_id()); ?>',
                'productName': '<?php echo esc_js($product->get_name()); ?>',
                'productPrice': <?php echo $product->get_price(); ?>,
                'currency': '<?php echo get_woocommerce_currency(); ?>'
            });
        </script>
        <?php
    }
}

Then in GTM:

  1. Create Custom HTML Tag
  2. Add Meta Pixel event code: fbq('track', 'ViewContent', {...})
  3. Trigger: Custom Event productView

Advanced Matching with Events

Include user data for better attribution:

add_action('woocommerce_thankyou', 'track_purchase_with_advanced_matching');
function track_purchase_with_advanced_matching($order_id) {
    $order = wc_get_order($order_id);

    // Build advanced matching parameters (hashed)
    $user_data = array(
        'em' => hash('sha256', strtolower(trim($order->get_billing_email()))),
        'ph' => hash('sha256', preg_replace('/[^0-9]/', '', $order->get_billing_phone())),
        'fn' => hash('sha256', strtolower(trim($order->get_billing_first_name()))),
        'ln' => hash('sha256', strtolower(trim($order->get_billing_last_name()))),
        'ct' => hash('sha256', strtolower(trim($order->get_billing_city()))),
        'st' => hash('sha256', strtolower(trim($order->get_billing_state()))),
        'zp' => hash('sha256', preg_replace('/[^0-9]/', '', $order->get_billing_postcode())),
        'country' => hash('sha256', strtolower(trim($order->get_billing_country())))
    );
    ?>
    <script>
        fbq('track', 'Purchase', {
            value: <?php echo $order->get_total(); ?>,
            currency: '<?php echo $order->get_currency(); ?>'
        }, {
            eventID: 'wc_order_<?php echo $order_id; ?>'
        });

        // Update advanced matching data
        fbq('init', 'YOUR_PIXEL_ID', <?php echo json_encode($user_data); ?>);
    </script>
    <?php
}

Event Deduplication (Browser + CAPI)

When using both browser pixel and Conversions API, use eventID to prevent duplicate counting:

Browser event:

fbq('track', 'Purchase', {
    value: 99.99,
    currency: 'USD'
}, {
    eventID: 'unique_event_123456'
});

Server-side CAPI event:

$event_data = array(
    'event_name' => 'Purchase',
    'event_id' => 'unique_event_123456', // Same as browser
    'event_time' => time(),
    // ... other data
);

Meta will automatically deduplicate events with matching event_id values.

Testing and Validation

Meta Pixel Helper

Install Meta Pixel Helper Chrome extension:

  • Green: Events firing correctly
  • Yellow: Warnings
  • Red: Errors

Test Events Tool

  1. Meta Events Manager → Test Events
  2. Enter your website URL
  3. Browse site and verify events appear in real-time

Browser Console

// Check if pixel loaded
console.log(window.fbq);

// View all events fired
window.fbq.queue.forEach(item => console.log(item));

// Manually fire test event
fbq('trackCustom', 'TestEvent', {test: 'parameter'});

Performance Optimization

Conditional Event Loading

// Only load WooCommerce events on shop pages
add_action('wp_enqueue_scripts', 'conditional_fb_event_scripts');
function conditional_fb_event_scripts() {
    if (is_woocommerce() || is_cart() || is_checkout()) {
        wp_enqueue_script('wc-fb-events', get_stylesheet_directory_uri() . '/js/wc-fb-events.js', array('jquery'), '1.0', true);
    }
}

Common Issues

Events not firing:

  • Check Meta Pixel Helper for errors
  • Verify pixel initialized before event fires
  • Check browser console for JavaScript errors
  • Ensure caching plugins don't prevent script execution

Duplicate events:

  • Check for multiple pixel installations (plugin + manual)
  • Implement event deduplication with eventID
  • Remove redundant tracking code

See Tracking Troubleshooting for detailed debugging.

Next Steps

// SYS.FOOTER