WooCommerce Ajax Add to Cart facebook pixel event not working

生来就可爱ヽ(ⅴ<●) 提交于 2020-05-28 04:37:37

问题


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.

来源:https://stackoverflow.com/questions/61701437/woocommerce-ajax-add-to-cart-facebook-pixel-event-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!