Добавлен тестовый режим метрик

pull/36/head
Your Name 4 weeks ago
parent 2bc9c1b0b7
commit 4098b3c7b9
  1. 259
      wp-content/themes/cosmopet/global-functions/multisite-functions.php

@ -76,148 +76,185 @@ function custom_canonical_url() {
} }
/** /**
* Добавление событий контрибуции для FP Pixel * Добавление событий контрибуции для FP Pixel
* только на боевом сайте АЕ * только на боевом сайте АЕ
* */ */
if($site_env->site_mode == 'production' and $site_env->site_region == 'ae') { // if ($site_env->site_mode == 'production' && $site_env->site_region == 'ae') {
/* Передача просто по url */
// Проверка на тестовый режим для метрик
function is_gp_test_mode() {
if (isset($_GET['gp-test']) && $_GET['gp-test'] == '1') {
return true;
}
if (is_user_logged_in() && current_user_can('administrator')) {
return true;
}
return false;
}
add_action('wp_footer', 'add_facebook_pixel_events'); add_action('wp_footer', 'add_facebook_pixel_events');
function add_facebook_pixel_events() { function add_facebook_pixel_events() {
// 1. Событие AddToCart (Добавление в корзину) if (is_gp_test_mode()) return;
global $product;
// 1. ViewContent
if (is_product() && $product && $product->get_price() > 0) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'ViewContent', {
content_ids: ['<?php echo $product->get_id(); ?>'],
content_type: 'product',
value: <?php echo $product->get_price(); ?>,
currency: '<?php echo get_woocommerce_currency(); ?>'
});
});
</script>
<?php
}
// 2. InitiateCheckout
if (is_checkout() && !is_wc_endpoint_url('order-received') && WC()->cart && WC()->cart->get_cart_contents_count() > 0) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'InitiateCheckout');
});
</script>
<?php
}
// 3. AddToCart
if (is_product() || is_shop() || is_cart()) { if (is_product() || is_shop() || is_cart()) {
?> ?>
<script> <script>
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
jQuery(function($) { jQuery(function($) {
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) { $(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
var productId = $button.data('product_id') || ''; var productId = $button.data('product_id') || '';
var quantity = $button.data('quantity') || 1; var quantity = $button.data('quantity') || 1;
var productName = $button.data('product_sku') || var productName = $button.data('product_sku') ||
$button.closest('.product').find('.woocommerce-loop-product__title').text().trim() || 'Unknown'; $button.closest('.product').find('.woocommerce-loop-product__title').text().trim() || 'Unknown';
var priceElement = $button.closest('.product').find('.price .amount').text().replace(/[^0-9.]/g, '') || '0.00'; var priceElement = $button.closest('.product').find('.price .amount').text().replace(/[^0-9.]/g, '') || '0.00';
var currency = '<?php echo get_woocommerce_currency(); ?>'; // Динамическая валюта var currency = '<?php echo get_woocommerce_currency(); ?>';
// Событие для Facebook Pixel fbq('track', 'AddToCart', {
fbq('track', 'AddToCart', { content_ids: [productId],
content_ids: [productId], content_type: 'product',
content_type: 'product', value: parseFloat(priceElement) * quantity,
value: parseFloat(priceElement) * quantity, currency: currency
currency: currency });
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'add_to_cart',
'ecommerce': {
'currency': currency,
'value': parseFloat(priceElement) * quantity,
'items': [{
'item_id': productId,
'item_name': productName,
'price': parseFloat(priceElement),
'quantity': quantity
}]
}
});
}); });
});
});
</script>
<?php
}
// 4. AddPaymentInfo
if (is_checkout() && !is_wc_endpoint_url('order-received') && WC()->cart && WC()->cart->get_cart_contents_count() > 0) {
$currency = get_woocommerce_currency();
$cart_total = WC()->cart->get_total('edit');
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'AddPaymentInfo', {
value: <?php echo $cart_total; ?>,
currency: '<?php echo $currency; ?>'
});
// Событие для Google Analytics
window.dataLayer = window.dataLayer || []; window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ window.dataLayer.push({
'event': 'add_to_cart', 'event': 'add_payment_info',
'ecommerce': { 'ecommerce': {
'currency': currency, 'currency': '<?php echo $currency; ?>',
'value': parseFloat(priceElement) * quantity, 'value': <?php echo $cart_total; ?>
'items': [{
'item_id': productId,
'item_name': productName,
'price': parseFloat(priceElement),
'quantity': quantity
}]
} }
}); });
}); });
});
});
</script> </script>
<?php <?php
} }
// 2. Событие Purchase (Покупка) // 5. Purchase
if (is_wc_endpoint_url('order-received')) { if (is_wc_endpoint_url('order-received')) {
$order_id = absint(get_query_var('order-received')); $order_id = absint(get_query_var('order-received'));
if (!$order_id) return; if (!$order_id) return;
$order = wc_get_order($order_id); $order = wc_get_order($order_id);
if (!$order || ($order->get_status() !== 'processing' && $order->get_status() !== 'completed')) return; if (!$order || ($order->get_status() !== 'processing' && $order->get_status() !== 'completed')) return;
$items = []; $items = [];
foreach ($order->get_items() as $item) { foreach ($order->get_items() as $item) {
$product = $item->get_product(); $product = $item->get_product();
$items[] = [ $items[] = [
'item_id' => $product->get_id(), 'item_id' => $product->get_id(),
'item_name' => $product->get_name(), 'item_name' => $product->get_name(),
'price' => $product->get_price(), 'price' => $product->get_price(),
'quantity' => $item->get_quantity() 'quantity' => $item->get_quantity()
]; ];
} }
?> ?>
<script> <script>
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'Purchase', { fbq('track', 'Purchase', {
value: <?php echo $order->get_total(); ?>, value: <?php echo $order->get_total(); ?>,
currency: '<?php echo $order->get_currency(); ?>', currency: '<?php echo $order->get_currency(); ?>',
content_ids: [<?php echo implode(',', array_column($items, 'item_id')); ?>], content_ids: [<?php echo implode(',', array_column($items, 'item_id')); ?>],
content_type: 'product' content_type: 'product'
}); });
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'purchase',
'ecommerce': {
'currency': '<?php echo $order->get_currency(); ?>',
'value': <?php echo $order->get_total(); ?>,
'items': <?php echo json_encode($items); ?>
}
});
});
</script>
<?php
}
// 3. Событие AddPaymentInfo
if (is_checkout() && !is_wc_endpoint_url('order-received')) {
$currency = get_woocommerce_currency();
$cart_total = WC()->cart ? WC()->cart->get_total('edit') : 0;
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'AddPaymentInfo', {
value: <?php echo $cart_total; ?>,
currency: '<?php echo $currency; ?>'
});
window.dataLayer = window.dataLayer || []; window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ window.dataLayer.push({
'event': 'add_payment_info', 'event': 'purchase',
'ecommerce': { 'ecommerce': {
'currency': '<?php echo $currency; ?>', 'currency': '<?php echo $order->get_currency(); ?>',
'value': <?php echo $cart_total; ?> 'value': <?php echo $order->get_total(); ?>,
} 'items': <?php echo json_encode($items); ?>
}); }
}); });
</script> });
<?php </script>
} <?php
}
} }
/* Передача контрибуции со страницы "Спасибо" */
add_action('woocommerce_thankyou', 'send_purchase_to_metrika'); add_action('woocommerce_thankyou', 'send_purchase_to_metrika');
function send_purchase_to_metrika($order_id) function send_purchase_to_metrika($order_id) {
{ if (is_gp_test_mode()) return;
if (!$order_id)
return; // Проверка, что заказ существует if (!$order_id) return;
$order = wc_get_order($order_id); $order = wc_get_order($order_id);
if ($order->get_status() !== 'processing' && $order->get_status() !== 'completed') if ($order->get_status() !== 'processing' && $order->get_status() !== 'completed') return;
return; // Отправляем только для оплаченных заказов
$items = []; $items = [];
foreach ($order->get_items() as $item) { foreach ($order->get_items() as $item) {
$product = $item->get_product(); $product = $item->get_product();
$items[] = [ $items[] = [
'id' => $product->get_id(), 'id' => $product->get_id(),
'name' => $product->get_name(), 'name' => $product->get_name(),
'price' => $product->get_price(), 'price' => $product->get_price(),
'quantity' => $item->get_quantity() 'quantity' => $item->get_quantity()
]; ];
} }
// Получаем валюту заказа
$currency = $order->get_currency(); $currency = $order->get_currency();
?> ?>
<script> <script>
@ -235,7 +272,6 @@ if($site_env->site_mode == 'production' and $site_env->site_region == 'ae') {
} }
}); });
// Яндекс.Метрика
yaCounter96481053.reachGoal('purchase', { yaCounter96481053.reachGoal('purchase', {
'order_id': '<?php echo $order_id; ?>', 'order_id': '<?php echo $order_id; ?>',
'order_price': '<?php echo $order->get_total(); ?>', 'order_price': '<?php echo $order->get_total(); ?>',
@ -243,7 +279,6 @@ if($site_env->site_mode == 'production' and $site_env->site_region == 'ae') {
'items': <?php echo json_encode($items); ?> 'items': <?php echo json_encode($items); ?>
}); });
// Facebook Pixel
fbq('track', 'Purchase', { fbq('track', 'Purchase', {
value: <?php echo $order->get_total(); ?>, value: <?php echo $order->get_total(); ?>,
currency: '<?php echo $currency; ?>', currency: '<?php echo $currency; ?>',
@ -253,7 +288,7 @@ if($site_env->site_mode == 'production' and $site_env->site_region == 'ae') {
</script> </script>
<?php <?php
} }
} // }
// Отключаем кэширование для страниц товаров // Отключаем кэширование для страниц товаров
add_action('template_redirect', function() { add_action('template_redirect', function() {

Loading…
Cancel
Save