FB pixel

// Function that gets the Ajax data
add_action( 'wp_ajax_product_added_to_cart', 'wc_product_added_to_cart' );
add_action( 'wp_ajax_nopriv_product_added_to_cart', 'wc_product_added_to_cart' );
function wc_product_added_to_cart() {
    if ( isset($_POST['pid']) ){
        // Get an instance of the WCW_Product Object
        $product = wc_get_product( $_POST['pid'] );

        // Return the product price including taxes
        echo number_format( wc_get_price_including_tax( $product ), 2 );

        // OR =>the product price EXCLUDING taxes
        // echo number_format( wc_get_price_excluding_tax( $product ), 2 );
    }
    die(); // Alway at the end (to avoid server error 500)
}

// FB PiXELS HEAD Script (Initializing)
add_action( 'wp_head', 'fbpixels_head_script' );
function fbpixels_head_script() {
    ?>
    <script>
    !function(f,b,e,v,n,t,s)
    {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s)}(window, document,'script',
    'https://connect.facebook.net/en_US/fbevents.js');
    </script>
    <?php
}

// FB PiXELS Footer script Events
add_action( 'wp_footer', 'fbpixels_add_to_cart_script' );
function fbpixels_add_to_cart_script(){
    // HERE set your init reference
    $init_id = '1552143158136112';

    // HERE set the product currency code
    $currency = 'SEK';

    ## 0. Common script -  On ALL Pages
    ?>
    <script>
    fbq('init', <?php echo $init_id; ?>);
    fbq('track', 'PageView');
    <?php

    ## 1. On Checkout page
    if ( ! is_wc_endpoint_url( 'order-received' ) && is_checkout() ) {
    ?>
    fbq('track', 'InitiateCheckout');
    <?php

    ## 2. On Order received (thankyou)
    } elseif ( is_wc_endpoint_url( 'order-received' ) ) {
    global $wp;

    // Get the Order ID from Query vars
    $order_id  = absint( $wp->query_vars['order-received'] );

    if ( $order_id > 0 ){

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );
    ?>
    fbq('track', 'Purchase', {
        value:    <?php echo $order->get_total(); ?>,
        currency: '<?php echo $order->get_order_currency(); ?>',
    });
    <?php
    }
    ## 3. Other pages - (EXCEPT Order received and Checkout)
    } else {

    ?>
    jQuery(function($){
        if (typeof woocommerce_params === 'undefined')
            return false;

        var price;
        $('body').on( 'adding_to_cart', function(a,b,d){
            var sku = d.product_sku, // product Sku
                pid = d.product_id,  // product ID
                qty = d.quantity;    // Quantity

            $.ajax({
                url: woocommerce_params.ajax_url,
                type: 'POST',
                data: {
                    'action' : 'product_added_to_cart',
                    'sku'    : sku,
                    'pid'    : pid,
                    'qty'    : qty
                },
                success: function(result) {
                    // The FB Pixels script for AddToCart
                    if( result > 0 ){
                        fbq('track', 'AddToCart', {
                            value:    result,
                            currency: '<?php echo $currency; ?>',
                        });
                        console.log(result);
                    }
                }
            });
        });
    });
    <?php
    }
    ## For single product pages - Normal add to cart
    if( is_product() && isset($_POST['add-to-cart']) ){
        global $product;

        // variable product
        if( $product->is_type('variable') && isset($_POST['variation_id']) ) {
            $product_id = $_POST['variation_id'];
            $price = number_format( wc_get_price_including_tax( wc_get_product($_POST['variation_id']) ), 2 );
        }
        // Simple product
        elseif ( $product->is_type('simple') ) {
            $product_id = $product->get_id();
            $price = number_format( wc_get_price_including_tax( $product ), 2 );
        }
        $quantity = isset($_POST['quantity']) ? $_POST['quantity'] : 1;

        ?>
        fbq('track', 'AddToCart', {
            value:    <?php echo $price; ?>,
            currency: '<?php echo $currency; ?>',
        });
        <?php
    }
    ?>
    </script>
    <noscript>
    <img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=<?php echo $init_id; ?>&ev=PageView&noscript=1" />
    </noscript>
    <?php
}
Published
Categorized as wp