WooCommerce Ajax Add to Cart facebook pixel event not working

Viewed 1308

Add to Cart Facebook pixel event is not being triggered when adding product to cart with Ajax.

Here is my first output in head.

    <!-- WooCommerce Facebook Integration Begin -->
    <script <?php echo self::get_script_attributes(); ?>>

        <?php echo $this->get_pixel_init_code(); ?>

        fbq( 'track', 'PageView', <?php echo json_encode( self::build_params( [], 'PageView' ), JSON_PRETTY_PRINT | JSON_FORCE_OBJECT ) ?> );
        document.addEventListener('DOMContentLoaded', function() {
        jQuery && jQuery(function($){
        $('body').on( 'added_to_cart', function()
            {
            // Testing output on browser JS console
            console.log('added_to_cart'); 
        $( 'body' ).append( '<div class=\"wc-facebook-pixel-event-placeholder\"></div>' );


        });
    });
    }, false);
    </script>

When adding product to cart, "added_to_cart" is printed in console. So the add to cart Ajax is working.

Here is the function that is not being trigger with Ajax.

// AddToCart while AJAX is enabled
add_action( 'woocommerce_ajax_added_to_cart', [ $this, 'add_filter_for_add_to_cart_fragments' ] );

// Setups a filter to add an add to cart fragment whenever a product is added to the cart through Ajax.

public function add_filter_for_add_to_cart_fragments() {

            if ( 'no' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
                add_filter( 'woocommerce_add_to_cart_fragments', [ $this, 'add_add_to_cart_event_fragment' ] );
            }
        }

// Adds an add to cart fragment to trigger an AddToCart event.

public function add_add_to_cart_event_fragment( $fragments ) {

            if ( self::$isEnabled ) {

                $script = $this->pixel->get_event_script( 'AddToCart', [
                    'content_ids'  => $this->get_cart_content_ids(),
                    'content_type' => 'product',
                    'contents'     => $this->get_cart_contents(),
                    'value'        => $this->get_cart_total(),
                    'currency'     => get_woocommerce_currency(),
                ] );

                $fragments['div.wc-facebook-pixel-event-placeholder'] = '<div class="wc-facebook-pixel-event-placeholder">' . $script . '</div>';
            }

            return $fragments;
        }

I'm using latest Wordpress & WooCommerce with Facebook for WooCommerce plugin.

0 Answers
Related