Meta Pixel ViewContent and AddToCart for WooCommerce
Sends Meta (Facebook) Pixel "ViewContent" on product pages and "AddToCart" when products are added, so you can build retargeting audiences and optimize ads.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
if ( ! function_exists( 'is_product' ) ) {
return;
}
$view = null;
if ( is_product() ) {
$product = wc_get_product( get_queried_object_id() );
if ( $product ) {
$view = array(
'content_ids' => array( (string) $product->get_id() ),
'content_name' => $product->get_name(),
'content_type' => $product->is_type( 'variable' ) ? 'product_group' : 'product',
'value' => round( (float) wc_get_price_to_display( $product ), 2 ),
'currency' => get_woocommerce_currency(),
);
}
}
?>
<script>
(function () {
if (typeof fbq !== 'function') { return; }
var view = <?php echo wp_json_encode( $view ); ?>;
if (view) {
fbq('track', 'ViewContent', view);
var form = document.querySelector('form.cart');
if (form) {
form.addEventListener('submit', function () {
fbq('track', 'AddToCart', { content_ids: view.content_ids, content_type: 'product', value: view.value, currency: view.currency });
});
}
}
if (window.jQuery) {
jQuery(document.body).on('added_to_cart', function (e, f, h, button) {
var id = button && button.length ? button[0].getAttribute('data-product_id') : '';
fbq('track', 'AddToCart', { content_ids: id ? [String(id)] : [], content_type: 'product' });
});
}
})();
</script>
<?php
} );
Notes
Needs the Meta Pixel base code on the page.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.