Task:7359 | Разделение функции пикселя в отдельный файл

pull/36/head
Your Name 4 weeks ago
parent 841f458e86
commit e854446fb9
  1. 272
      wp-content/themes/cosmopet/global-functions/multisite-functions.php
  2. 135
      wp-content/themes/cosmopet/templates/head-pixel-functions.twig
  3. 1
      wp-content/themes/cosmopet/templates/layout.twig

@ -2,15 +2,13 @@
/* Start | Работа с проверкой мультисайтовости и стендов */ /* Start | Работа с проверкой мультисайтовости и стендов */
global $site_env; global $site_env;
$site_env = new SiteEnvironment(); // глобальный объект выполняющий проверку по домену $site_env = new SiteEnvironment();
class SiteEnvironment class SiteEnvironment {
{
public string $site_mode; public string $site_mode;
public string $site_region; public string $site_region;
public bool $is_gp_test_mode; public bool $is_gp_test_mode;
public function __construct(string $host = null) public function __construct(string $host = null) {
{
$map = [ $map = [
'cosmopet.ru' => ['mode' => 'production', 'region' => 'ru'], 'cosmopet.ru' => ['mode' => 'production', 'region' => 'ru'],
'cosmopet.ae' => ['mode' => 'production', 'region' => 'ae'], 'cosmopet.ae' => ['mode' => 'production', 'region' => 'ae'],
@ -18,275 +16,65 @@ class SiteEnvironment
'cosmopet-test-ru.cp.good-production.xyz' => ['mode' => 'develope', 'region' => 'ru'], 'cosmopet-test-ru.cp.good-production.xyz' => ['mode' => 'develope', 'region' => 'ru'],
'cosmopet-test-ae.cp.good-production.xyz' => ['mode' => 'develope', 'region' => 'ae'], 'cosmopet-test-ae.cp.good-production.xyz' => ['mode' => 'develope', 'region' => 'ae'],
]; ];
$host = strtolower($host ?: $_SERVER['SERVER_NAME']); $host = strtolower($host ?: $_SERVER['SERVER_NAME']);
$config = $map[$host] ?? ['mode' => 'develope', 'region' => 'unknown']; $config = $map[$host] ?? ['mode' => 'develope', 'region' => 'unknown'];
$this->site_mode = $config['mode']; $this->site_mode = $config['mode'];
$this->site_region = $config['region']; $this->site_region = $config['region'];
// Логика тестового режима
$this->is_gp_test_mode = (isset($_GET['gp-test']) && $_GET['gp-test'] == '1') || (is_user_logged_in() && current_user_can('administrator')); $this->is_gp_test_mode = (isset($_GET['gp-test']) && $_GET['gp-test'] == '1') || (is_user_logged_in() && current_user_can('administrator'));
} }
} }
add_filter('timber/twig', function (\Twig\Environment $twig) { add_filter('timber/twig', function (\Twig\Environment $twig) {
global $site_env; global $site_env;
$twig->addGlobal('site_env', $site_env);
$twig->addGlobal('site_region', $site_env->site_region); $twig->addGlobal('header_scripts', get_field('header_scripts', 'option'));
$twig->addGlobal('site_mode', $site_env->site_mode);
$twig->addGlobal('header_scripts', get_field('header_scripts', 'option')); // со страницы "Общих настроек контента ACF"
return $twig; return $twig;
}); });
/* End | Работа с проверкой мультисайтовости и стендов */ /* End | Работа с проверкой мультисайтовости и стендов */
add_filter('woocommerce_currency_symbol', function($currency_symbol, $currency) {
return $currency === 'AED' ? 'AED' : $currency_symbol;
}, 10, 2);
add_filter('woocommerce_currency_symbol', 'change_aed_currency_symbol', 10, 2);
function change_aed_currency_symbol($currency_symbol, $currency) {
if ($currency == 'AED') {
$currency_symbol = 'AED';
}
return $currency_symbol;
}
// Отключаем канонические ссылки и hreflang от Yoast SEO
add_filter('wpseo_canonical', '__return_false'); add_filter('wpseo_canonical', '__return_false');
add_filter('wpseo_opengraph_url', '__return_false'); // Отключаем OG URL add_filter('wpseo_opengraph_url', '__return_false');
add_filter('wpseo_add_x_default_hreflang', '__return_false'); // Отключаем hreflang от Yoast add_filter('wpseo_add_x_default_hreflang', '__return_false');
add_filter('wpseo_disable_adjacent_rel_links', '__return_true'); // Отключаем соседние rel-ссылки add_filter('wpseo_disable_adjacent_rel_links', '__return_true');
// Добавляем каноническую ссылку add_action('wp_head', function() {
add_action('wp_head', 'custom_canonical_url', 5);
function custom_canonical_url() {
if (!is_admin()) { if (!is_admin()) {
// Защищаем от дублирования
static $canonical_added = false; static $canonical_added = false;
if ($canonical_added) { if ($canonical_added) return;
return;
}
$canonical_added = true; $canonical_added = true;
$current_url = strtok(trailingslashit(home_url($_SERVER['REQUEST_URI'])), '?');
// Формируем текущий URL без лишних параметров
$current_url = trailingslashit(home_url($_SERVER['REQUEST_URI']));
// Удаляем возможные параметры запроса, если они не нужны
$current_url = strtok($current_url, '?');
echo '<link rel="canonical" href="' . esc_url($current_url) . '" />' . "\n"; echo '<link rel="canonical" href="' . esc_url($current_url) . '" />' . "\n";
} }
} }, 5);
/**
* Добавление событий контрибуции для FP Pixel
* Только на боевом сайте AE, с учетом тестового режима через site_env->is_gp_test_mode
*/
if (isset($site_env) && $site_env->site_mode === 'production' && $site_env->site_region === 'ae' && !$site_env->is_gp_test_mode) {
add_action('wp_footer', 'add_facebook_pixel_events');
function add_facebook_pixel_events() {
global $site_env, $product;
if ($site_env->is_gp_test_mode) return;
// 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()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
jQuery(function($) {
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
var productId = $button.data('product_id') || '';
var quantity = $button.data('quantity') || 1;
var productName = $button.data('product_sku') ||
$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 currency = '<?php echo get_woocommerce_currency(); ?>';
fbq('track', 'AddToCart', { add_action('wp_head', function() {
content_ids: [productId], global $site_env;
content_type: 'product', $show_pixel = false;
value: parseFloat(priceElement) * quantity,
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; ?>'
});
window.dataLayer = window.dataLayer || []; // Для продакшена
window.dataLayer.push({ if ($site_env->site_mode === 'production' && $site_env->site_region === 'ae') {
'event': 'add_payment_info', $show_pixel = true;
'ecommerce': {
'currency': '<?php echo $currency; ?>',
'value': <?php echo $cart_total; ?>
}
});
});
</script>
<?php
} }
// 5. Purchase // Для тестовых стендов AE
if (is_wc_endpoint_url('order-received')) { if ($site_env->site_mode === 'develope' && $site_env->site_region === 'ae') {
$order_id = absint(get_query_var('order-received')); $show_pixel = true;
if (!$order_id) return;
$order = wc_get_order($order_id);
if (!$order || ($order->get_status() !== 'processing' && $order->get_status() !== 'completed')) return;
$items = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = [
'item_id' => $product->get_id(),
'item_name' => $product->get_name(),
'price' => $product->get_price(),
'quantity' => $item->get_quantity()
];
} }
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'Purchase', {
value: <?php echo $order->get_total(); ?>,
currency: '<?php echo $order->get_currency(); ?>',
content_ids: [<?php echo implode(',', array_column($items, 'item_id')); ?>],
content_type: 'product'
});
window.dataLayer = window.dataLayer || []; if ($show_pixel && !$site_env->is_gp_test_mode) {
window.dataLayer.push({ $context = [
'event': 'purchase', 'pixel_event_type' => 'AddToCart', // или определите логику
'ecommerce': { 'currency' => get_woocommerce_currency(),
'currency': '<?php echo $order->get_currency(); ?>', // добавьте другие переменные при необходимости
'value': <?php echo $order->get_total(); ?>,
'items': <?php echo json_encode($items); ?>
}
});
});
</script>
<?php
}
}
add_action('woocommerce_thankyou', 'send_purchase_to_metrika');
function send_purchase_to_metrika($order_id) {
global $site_env;
if ($site_env->is_gp_test_mode) return;
if (!$order_id) return;
$order = wc_get_order($order_id);
if ($order->get_status() !== 'processing' && $order->get_status() !== 'completed') return;
$items = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = [
'id' => $product->get_id(),
'name' => $product->get_name(),
'price' => $product->get_price(),
'quantity' => $item->get_quantity()
]; ];
} \Timber\Timber::render('templates/head-pixel-functions.twig', $context);
$currency = $order->get_currency();
?>
<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
'ecommerce': {
'purchase': {
'actionField': {
'id': '<?php echo $order_id; ?>',
'revenue': '<?php echo $order->get_total(); ?>',
'currency': '<?php echo $currency; ?>'
},
'products': <?php echo json_encode($items); ?>
}
} }
}); });
yaCounter96481053.reachGoal('purchase', {
'order_id': '<?php echo $order_id; ?>',
'order_price': '<?php echo $order->get_total(); ?>',
'currency': '<?php echo $currency; ?>',
'items': <?php echo json_encode($items); ?>
});
fbq('track', 'Purchase', {
value: <?php echo $order->get_total(); ?>,
currency: '<?php echo $currency; ?>',
content_ids: [<?php echo implode(',', array_column($items, 'id')); ?>],
content_type: 'product'
});
</script>
<?php
}
}
// Отключаем кэширование для страниц товаров
add_action('template_redirect', function() { add_action('template_redirect', function() {
if (is_product()) { if (is_product()) {
header('Cache-Control: no-cache, no-store, must-revalidate'); header('Cache-Control: no-cache, no-store, must-revalidate');

@ -0,0 +1,135 @@
{# header_scripts_pixel.twig #}
{# Проверка переменных перед рендерингом #}
{% if pixel_event_type == 'ViewContent' and product %}
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'ViewContent', {
content_ids: ['{{ product.id }}'],
content_type: 'product',
value: {{ product.price|number_format(2, '.', '') }},
currency: '{{ currency }}'
});
});
</script>
{% endif %}
{% if pixel_event_type == 'InitiateCheckout' %}
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'InitiateCheckout');
});
</script>
{% endif %}
{% if pixel_event_type == 'AddToCart' %}
<script>
document.addEventListener('DOMContentLoaded', function() {
jQuery(function($) {
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
var productId = $button.data('product_id') || '';
var quantity = $button.data('quantity') || 1;
var productName = $button.data('product_sku') ||
$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 currency = '{{ currency }}';
fbq('track', 'AddToCart', {
content_ids: [productId],
content_type: 'product',
value: parseFloat(priceElement) * quantity,
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>
{% endif %}
{% if pixel_event_type == 'AddPaymentInfo' %}
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'AddPaymentInfo', {
value: {{ cart_total|number_format(2, '.', '') }},
currency: '{{ currency }}'
});
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'add_payment_info',
'ecommerce': {
'currency': '{{ currency }}',
'value': {{ cart_total|number_format(2, '.', '') }}
}
});
});
</script>
{% endif %}
{% if pixel_event_type == 'Purchase' and order %}
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'Purchase', {
value: {{ order.total|number_format(2, '.', '') }},
currency: '{{ order.currency }}',
content_ids: [{{ order.content_ids|join(',') }}],
content_type: 'product'
});
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'purchase',
'ecommerce': {
'currency': '{{ order.currency }}',
'value': {{ order.total|number_format(2, '.', '') }},
'items': {{ order.items|json_encode()|raw }}
}
});
});
</script>
<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
'ecommerce': {
'purchase': {
'actionField': {
'id': '{{ order.id }}',
'revenue': '{{ order.total|number_format(2, '.', '') }}',
'currency': '{{ order.currency }}'
},
'products': {{ order.items|json_encode()|raw }}
}
}
});
yaCounter96481053.reachGoal('purchase', {
'order_id': '{{ order.id }}',
'order_price': '{{ order.total|number_format(2, '.', '') }}',
'currency': '{{ order.currency }}',
'items': {{ order.items|json_encode()|raw }}
});
fbq('track', 'Purchase', {
value: {{ order.total|number_format(2, '.', '') }},
currency: '{{ order.currency }}',
content_ids: [{{ order.content_ids|join(',') }}],
content_type: 'product'
});
</script>
{% endif %}

@ -10,6 +10,7 @@
{% if site_mode == 'production' %} {% if site_mode == 'production' %}
{{ header_scripts }} {{ header_scripts }}
{% endif %} {% endif %}
</head> </head>
<body class="{{bodyClass}}"> <body class="{{bodyClass}}">

Loading…
Cancel
Save