In most cases executing a marketing strategy involves the use of paid advertisement such as Googles Ad Network, Facebook and Instagram, Pinterest or Twitter. While not all before mentioned channels may be applicable for your marketing strategy, one key component is absolutely vital for the success of paid campaigns in all of them: Data collection.
Data is the most important resource for your business in the 21st century. Any data not collected, even if unused at this point in time, is a loss of money in the long run. And as every dollar counts and ROI and profitability are key metrics for all businesses around the world, this tutorial aims to help beginners to install marketing pixels to a WooCommerce Shop without the use of clunky or paid plugins. With minor tweaks this way of implementation can be used for other shopping systems such as Magento, PrestaShop or even Node App.
Not relying on a Plugin to implement your Pixel allows you to customize events and set your own trackable metrics for your customer journey and funnels. If deeper integrations are needed for your business, let’s connect and strategize together.
What is a Marketing Pixel?
As much as we all want to see other pages data in e.g. Google Analytics the best one can do is usually guesstimate other pages metrics. Same applies to Facebook or Google which don’t know what happens once an advertisement is clicked and their users leave the site and visit your business. Marketing Pixel solve this cross-site issue by implementing legal scripts that report data back to the advertisement platform.
In return for your data the platform grants more features to advertise and better matching to find similar people to those who matched the reported events from a businesses website. Pixel code on your website is not the only way to report this data to the platform (notice how Amazon does not have a Pixel installed), but among the easiest and most cost efficient ones.
Why is it called a Pixel? Because with every implementation an invisible image with the size of one Pixel is hidden in your website reacting to triggers.
Implementing the Pixel base code
All Pixel follow the same principles. A javascript base code is loaded on all pages of a website which already passes the pageview parameter to the platform you are advertising with. We use the same strategy to implement all of them in our example WooCommerce store based on WordPress. We assume you use a child theme with a functions.php or registered your own plugin to implement the following code.
<?php
function eveel_base_pixel(){
?>
<!-- Facebook Pixel Code -->
<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');
fbq('init', 'YOUR_ID_HERE'); //Pixel ID
fbq('track', 'PageView');
</script>
<noscript>
<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=YOURI_ID_HERE&ev=PageView&noscript=1"/>
</noscript>
<!-- End Facebook Pixel Code -->
<?
}
add_action('wp_head', 'eveel_base_pixel');
Do not forget to add your own Pixel ID in both the <script> and <noscript> part of the code above. Now there would be numerous tricks to load this pixel. A delay of a couple seconds before sending the event trigger, loading the code with a different hook instead of using wp_head, waiting for the entire page to load before the pixel itself tiggers or use defer to load the script. But as it is already loading asynchronously for the most part concentrating on event triggers has priority for the initial setup.
Standard Pixel Events
As a WordPress WooCommerce store is the given example of this guide relevant shopping triggers will be introduced next. Implementation in this section differs slightly between for example Facebook and Pinterest. The main events a shop needs to look at are the following:
- View Product
- Add to Cart
- Purchase
View Product is the simplest one as WooCommerce already offers conditional parameters to check if the user currently is on a product page or not. This will extend the PageView trigger from the base code which will trigger even on blog posts or the shops about us page. Facebook calls this parameter ViewContent.
<?php
function eveel_facebook_product_view()
{
if( is_product() ) //Check if user on product page
{
$product = new WC_Product( get_the_ID() );
$sku = $product->get_sku();
$name = $product->get_title();
$cat = $product->get_categories();
?>
<script>
fbq('track', 'ViewContent',
{
content_ids: '<?php echo $sku ?>',
content_name: '<?php echo $name ?>',
content_category: '<?php echo $cat ?>'
});
</script>
<?
}
}
add_action( 'wp_footer', 'eveel_pint_product_view' );
Along with the ViewContent trigger we pushed a few more product information. Sending more data along with the basic trigger enables more advertisement solutions and more specific and sophisticated remarketing methods when segmenting visitors.
Integrating the Purchase trigger is equally simple as most shopping systems redirect buyers to a “thank you page” once a purchase is confirmed. WooCommerce also offers a useful conditional parameter checking, if the thank you page was called. The code for the Facebook Pixel is as follows:
<?php
function pinterest_tracking( $order_id ) {
$order = wc_get_order( $order_id );
$sku = $order->get_sku();
$order_total = $order->get_total();
$order_quantity = $order->get_item_count();
$order_sub_price = $order_item->get_subtotal()
$order_currency = $order->get_currency();?>
<script>
fbq('track', 'Purchase',
{
value: '<?php echo $order_total ?>',
currency: '<?php echo $order_currency ?>'
content: [
quantity: '<?php echo $order_quantity ?>',
item_price: '<?php echo $sub_price ?>',
}]);
</script>
<?php
}
add_action( 'woocommerce_thankyou', 'pinterest_tracking' );
This is the first example where nesting becomes necessary to push the full order details to the pixel data layer. First the whole order is accessed including the total amount. Then each product single product, the ordered quantity and subtotal price inside this order is nested in a loop. Many more parameters of the order could be pushed here, but to keep it simple we only added the most important ones to the code.
The Add to Cart tracking is the one most people struggle with, because in most cases it has to be triggered on a button click. This can either be achieved with a jQuery script or a POST request with a few lines of PHP code. As jQuery often runs into compatibility issues with different WooCommerce themes and plugins we demonstrate the latter in the following code example.
<?php
function eveel_added_to_cart_event()
{
if( isset($_POST['add-to-cart']) && isset($_POST['quantity']) ) {
$quantity = $_POST['quantity'];
$product_id = isset($_POST['variation_id']) ? $_POST['variation_id'] : $_POST['add-to-cart'];
?>
<script>
fbq('track', 'AddToCart', {
currency: 'USD',
contents: [{
product_id: '<?php echo $product_id ?>',
order_quantity: '<?php echo $quantity ?>'
}]
});
</script>
<?php
}
}
add_action('wp_footer', 'eveel_added_to_cart_event');
To get the correct total value of an add to cart event a nested structure similar to the checkout event is used. The code also ensures that, for products with multiple variations (colours, sizes, …), they are also properly pushed once the WooCommerce event is triggered.
Just for reference, here the short version of the jQuery script needed to fire an event once products are added to the cart by the user.
<script>
jQuery'body'.on('added_to_cart',function(){
fbq('track','AddToCart');
});
<script>
Advanced Pixel Events
As we covered the standard events already, there is plenty more to discover before we look into creating our own events for advertisement purposes. These more advanced events are ideal to further specify potential ad optimization or niche shops and other non e-commerce businesses.
The following Events are already included in Facebooks documentation:
- AddPaymentInfo
- AddToWishlist
- CompleteRegistration
- Contact
- Customize Product
- Donate
- FindLocation
- InitiateCheckout
- Lead
- Schedule
- Search
- StartTrial
- SubmitApplication
- Subscribe
The best about these is that due to the huge amount of data Facebook collects, the company can guess some of these events and automatically pushes the data to your Pixel. This of course is not the kind of implementation we are after with this guides as some of these functionalities are absolutely vital to a functioning advertisement campaign and relying on guessing is an admins nightmare.
Most websites do not have all the respective functionalities and thus only need a few of the above mentioned events added to their site. But to ensure absolute compatibility, we recommend to set these up manually.
Every page is different and in most cases these events will be added to a button on a website. Use and modify the jQuery script posted above and enter the parameters you want to push. Pinterest, GoogleAds and others also offer their own set of advanced events.
Custom Events
Of course it is also possible to create your very own events and parameters. We always emphasize with our work that every business is different and has there own needs. Also, naming all events the way you prefer makes it much easier for intra team communication. We saw people Hacking their own “Product submitted”-Events to the available Lead event overwriting their Newsletter signup, which was then mapped as Lead. Do not do this.
So how are custom events set up? It’s simple and follows the exact same procedure as the events displayed above. This specific example follows the idea above to track the submission of a review
<input name="submit" type="submit" class="submitReview" value="Submit">
//Add jQuery tracking
<script>
jQuery('body').on('added_to_cart',(function($){
$(".submitReview").submit(function(){
fbq('trackCustom', 'ReviewSubmitted');});
});
</script>
Further parameters could be added to also push for example the product reviewed or to check if the user is logged in. Just grab any of those like shown in the example before.
Another options would be an on click event on a button itself. To implement this code theme files need to be edited and this method is only recommended for advanced user.
<button class="livechat" onClick="ChatOpened();">
//Code for this button
<script>
function ChatOpened(){
fbq('trackCustom','ChatOpened');
}
</script>
Tipp: Make sure to properly use onclick() or onsubmit() in their respective cases!
Tweaks for better data collection
Tracking more is not always the way to go to improve advertisement efforts. If the quality of the data a business collects is heavily diluted with low quality inputs costs could actually increase. Because of these I want to discuss some edge cases that should be considered.
Delaying Pixel Events
The average bounce rate for websites is above 50%. With so many users leaving without meaningful interactions or often even before the page loaded, why not exclude these users from marketing pixels? Wrapping the actual code pushing the data to the Network in a simple function solves this problem.
<script>
var seconds = 5;
setTimeout(function() {
fbq('track', 'ViewContent');
}, seconds * 1000);
</script>
This simple function forces the code to wait for 5 seconds until it is pushing data. If the user leaves before no data will be forwarded. This is also great for newspapers and magazines to track engaged readers or after clicking a play button on a video.
Scrolling and Pixel Events
While delaying the pixel event does a great job in most cases, another option to ensure interaction is tracking the actual scroll depths. If a user reaches the end of a page, we can assume they read the actual content. Tracking can be done for any depth and in this example we use percentages over pixels.
<?php
function eveel_scroll_tracking()
{
if( is_product() )
{
?>
<script>
var executeWhenReachedPagePercentage = function(percentage, callback) {
if (typeof percentage !== 'number') {
console.error(
'First parameter must be a number, got',
typeof percentage,
'instead',
);
}
if (typeof callback !== 'function') {
console.error(
'Second parameter must be a function, got',
typeof callback,
'instead',
);
}
function getDocumentLength() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
)
}
function getWindowLength() {
return window.innerHeight ||
(document.documentElement || document.body).clientHeight;
}
function getScrollableLength() {
if (getDocumentLength() > getWindowLength()) {
return getDocumentLength() - getWindowLength();
} else {
return 0;
}
}
var scrollableLength = getScrollableLength();
window.addEventListener("resize", function(){
scrollableLength = getScrollableLength();
}, false)
function getCurrentScrolledLengthPosition() {
return window.pageYOffset ||
(document.documentElement || document.body.parentNode || document.body).scrollTop;
}
function getPercentageScrolled() {
if (scrollableLength == 0) {
return 100;
} else {
return getCurrentScrolledLengthPosition() / scrollableLength * 100;
}
}
var executeCallback = (function() {
var wasExecuted = false;
return function() {
if (!wasExecuted && getPercentageScrolled() > percentage) {
wasExecuted = true;
callback();
}
};
})();
if (getDocumentLength() == 0 ||
(getWindowLength()/getDocumentLength() * 100 >= percentage)) {
callback();
} else {
window.addEventListener('scroll', executeCallback, false);
}
};
executeWhenReachedPagePercentage(25, function() {
fbq('trackCustom', 'ScrollTracking', {'depth': '25%'});
});
executeWhenReachedPagePercentage(50, function() {
fbq('trackCustom', 'ScrollTracking', {'depth': '50%'});
});
executeWhenReachedPagePercentage(75, function() {
fbq('trackCustom', 'ScrollTracking', {'depth': '75%'});
});
executeWhenReachedPagePercentage(99, function() {
fbq('trackCustom', 'ScrollTracking', {'depth': '100%'});
});
</script>
<?
}
}
add_action( 'wp_footer', 'eveel_scroll_tracking' );
This would add the script directly into WordPress on every product page possible. For landing pages or content marketing efforts created in the post section of WordPress the is_single() conditional could be used instead. This reference solution loads all events together with the rest of the website and constantly checks if the respect scroll depth was reached. In order to save some load speed advanced users may want to implement scrolldepth.js or similar libraries.
Time based Pixel Events
Another useful event to track is the actual time users spent on a page. This setting is already included within the facebook base pixel, but it does not allow advertisers to track by specific numbers and only gives access to add three different ranges of users to add to a custom audience.
This implementation is complicated, because to track the time on page in an optimal way the pixel needs to understand the difference between active and inactive time on page. This will be covered in a later tutorial as its implementation is way more advanced than the here covered methods.
Create powerful Custom Audiences
With all the events implemented in this event businesses will be able to create powerful custom audiences on any advertisement platform. It’s key for successful campaigns to combine these events to increase RoAS (Return on Advertisement Spending). Conditionals are key to create and target audiences with optimized advertisement.
Think of the following scenarios that can be targeted with the events shown in this guide:
- Regular Customers spending over 200$ per order and 60 days without a purchase.
- No purchase after spending 95% more time than the average user on page.
- Abandoned Cart after adding 3 products to basket and signing up for the newsletter.
Important to note is, that these (and endless more combinations) also act as indicators which factors of a businesses page or store can be optimized to increase the conversion rate. If advertisement towards these custom audiences is unsuccessful there may be essential issues with specific parts of the page.
Why not simply use a plugin?
Some companies like Facebook offer their own WordPress plugin to pixel your website and while thats a very convenient method, they also want to force other products like their customer chat on your site. Companies like Pinterest even recommend third party plugins that offer a paid pro version for advanced features. Bug fixing, security fixes, loading speed and other points of failure are obviously excluded in those cases.
If all you are looking for is basic pixel setup both these options are on a good enough basis, but we want to teach you how not to rely on a third party and maybe add custom events that are unique to your business.
Why not use Google Tag Manager?
We do and in most cases even prefer our optimized version of the Tag Manager. But as stated numerous times, every business is different and for a lot of clients an implementation via Google Tag Manager is an actual disadvantage.
With new strategies such as tracking events we also always recommend to test in a development environment to test and optimize the code before moving it into a live environment and push it through the Tag Manager. One of the most important parts of Marketing is A/B-Testing and the same applies here.
There will be another Guide and our complete and highly optimized Tag Manager for you to use in the future.
Need help with your Marketing and Development efforts?
In this guide we covered numerous options to rocket start Pixel tracking optimization, but sadly can not cover all cases. We are happy to help your marketing efforts and make your business collect the data that counts and converts.
A sophisticated setup is key to not die trying and waste the whole marketing budget and get no return on your dollars spent. Just drop us a message and let’s discuss your project together
Leave a Reply