在WooCommerce中跟踪Facebook像素的添加购物车和提交订单事件,可以帮助商家更好地理解用户在网站上的行为,并优化广告投放策略。以下是相关的基础概念、优势、类型、应用场景以及如何实现这些跟踪事件的详细解答。
Facebook像素是一种用于跟踪网站访问者行为的代码片段。它可以捕获用户在网站上的各种事件,如页面浏览、添加到购物车、提交订单等,并将这些数据发送到Facebook,以便商家可以进行广告优化和分析。
以下是在WooCommerce中添加Facebook像素代码并跟踪添加购物车和提交订单事件的步骤:
首先,你需要在Facebook广告管理平台创建一个像素,并获取相应的代码。
将获取到的像素代码添加到WooCommerce网站的头部或底部。通常可以在主题的functions.php
文件中进行如下操作:
function add_facebook_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_PIXEL_ID_HERE');
fbq('track', 'PageView');
</script>
<noscript>
<img height="1" width="1" src="https://www.facebook.com/tr?id=YOUR_PIXEL_ID_HERE&ev=PageView&noscript=1"/>
</noscript>
<!-- End Facebook Pixel Code -->
<?php
}
add_action('wp_head', 'add_facebook_pixel');
在WooCommerce的functions.php
文件中添加以下代码来跟踪添加到购物车的事件:
add_action('woocommerce_add_to_cart', 'track_add_to_cart_event');
function track_add_to_cart_event() {
if (function_exists('fbq')) {
global $woocommerce;
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['add-to-cart']));
$product_name = get_the_title($product_id);
$quantity = absint($_POST['quantity']);
$price = get_post_meta($product_id, '_regular_price', true);
fbq('trackCustom', 'AddToCart', {
'content_name': $product_name,
'content_category': '',
'content_ids': [$product_id],
'content_type': 'product',
'value': $price,
'currency': get_woocommerce_currency(),
'quantity': $quantity
});
}
}
同样在functions.php
文件中添加以下代码来跟踪订单提交事件:
add_action('woocommerce_thankyou', 'track_purchase_event', 10, 1);
function track_purchase_event($order_id) {
if (function_exists('fbq')) {
$order = wc_get_order($order_id);
$items = $order->get_items();
$total = $order->get_total();
$currency = $order->get_currency();
$items_data = [];
foreach ($items as $item_key => $item) {
$product = $item->get_product();
$items_data[] = [
'id' => $product->get_id(),
'name' => $product->get_name(),
'price' => $product->get_price(),
'quantity' => $item->get_quantity()
];
}
fbq('track', 'Purchase', [
'value': $total,
'currency': $currency,
'content_type': 'product',
'content_ids': array_column($items_data, 'id'),
'items': $items_data
]);
}
}
问题1:像素代码未正确加载
wp_head
钩子中,并清除浏览器缓存和服务器缓存。问题2:事件未被捕获
通过以上步骤,你可以在WooCommerce中成功实现Facebook像素的添加购物车和提交订单事件的跟踪。
领取专属 10元无门槛券
手把手带您无忧上云