You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
cosmopet-architecture/wp-content/themes/cosmopet/global-functions/multisite-functions.php

403 lines
16 KiB

<?php
/* Start | Работа с проверкой мультисайтовости и стендов */
global $site_env;
$site_env = new SiteEnvironment();
class SiteEnvironment {
public string $site_mode;
public string $site_region;
public bool $is_gp_test_mode;
public function __construct(string $host = null) {
$map = [
'cosmopet.ru' => ['mode' => 'production', 'region' => 'ru'],
'cosmopet.ae' => ['mode' => 'production', 'region' => 'ae'],
'cosmopet-test-dumb.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'],
];
$host = strtolower($host ?: $_SERVER['SERVER_NAME']);
$config = $map[$host] ?? ['mode' => 'develope', 'region' => 'unknown'];
$this->site_mode = $config['mode'];
$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'));
}
}
add_filter('timber/twig', function (\Twig\Environment $twig) {
global $site_env;
$twig->addGlobal('site_region', $site_env->site_region);
$twig->addGlobal('site_env', $site_env);
$twig->addGlobal('header_scripts', get_field('header_scripts', 'option'));
return $twig;
});
/* End | Работа с проверкой мультисайтовости и стендов */
add_filter('woocommerce_currency_symbol', function($currency_symbol, $currency) {
return $currency === 'AED' ? 'AED' : $currency_symbol;
}, 10, 2);
add_filter('wpseo_canonical', '__return_false');
add_filter('wpseo_opengraph_url', '__return_false');
add_filter('wpseo_add_x_default_hreflang', '__return_false');
add_filter('wpseo_disable_adjacent_rel_links', '__return_true');
add_action('wp_head', function() {
if (!is_admin()) {
static $canonical_added = false;
if ($canonical_added) return;
$canonical_added = true;
$current_url = strtok(trailingslashit(home_url($_SERVER['REQUEST_URI'])), '?');
echo '<link rel="canonical" href="' . esc_url($current_url) . '" />' . "\n";
}
})
/**
* Добавление событий контрибуции для FP Pixel
* только на боевом сайте АЕ
*/
if ($site_env->site_mode == 'production' && $site_env->site_region == 'ae') {
// Проверка на тестовый режим для метрик
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');
function add_facebook_pixel_events() {
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()) {
?>
<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', {
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>
<?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({
'event': 'add_payment_info',
'ecommerce': {
'currency': '<?php echo $currency; ?>',
'value': <?php echo $cart_total; ?>
}
});
});
</script>
<?php
}
// 5. Purchase
if (is_wc_endpoint_url('order-received')) {
$order_id = absint(get_query_var('order-received'));
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 || [];
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
}
}
add_action('woocommerce_thankyou', 'send_purchase_to_metrika');
function send_purchase_to_metrika($order_id) {
if (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()
];
}
$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
}
}
// Функция событий Meta Pixel
add_action('wp_head', function() {
global $site_env;
$show_pixel = false;
// Для продакшена
if ($site_env->site_mode === 'production' && $site_env->site_region === 'ae') {
$show_pixel = true;
}
// Для тестовых стендов AE
if ($site_env->site_mode === 'develope' && $site_env->site_region === 'ae') {
$show_pixel = true;
}
// Дополнительные проверки
$skip_tracking = false;
// Исключаем админов
if (current_user_can('administrator')) {
$skip_tracking = true;
}
// Исключаем gp-test режим
if ($site_env->is_gp_test_mode) {
$skip_tracking = true;
}
// Исключаем если есть параметр gp-test=1 в URL
if (isset($_GET['gp-test']) && $_GET['gp-test'] == '1') {
$skip_tracking = true;
}
if ($show_pixel && !$skip_tracking) {
$context = [
'currency' => get_woocommerce_currency(),
];
// Определяем тип страницы и подготавливаем данные
if (is_product()) {
// Страница товара - ViewContent
global $product;
if ($product && $product instanceof WC_Product) {
$context['pixel_event_type'] = 'ViewContent';
$context['product'] = [
'id' => $product->get_id(),
'name' => $product->get_name(),
'price' => floatval($product->get_price()),
'sku' => $product->get_sku(),
'category' => wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names'])[0] ?? '',
];
}
}
elseif (is_checkout() && !is_order_received_page()) {
// Страница чекаута - InitiateCheckout
$context['pixel_event_type'] = 'InitiateCheckout';
if (WC()->cart && !WC()->cart->is_empty()) {
$context['cart_total'] = floatval(WC()->cart->get_total('edit'));
$context['cart_items'] = [];
$context['content_ids'] = [];
foreach (WC()->cart->get_cart() as $cart_item) {
$product = $cart_item['data'];
if ($product && $product instanceof WC_Product) {
$item_data = [
'item_id' => $product->get_id(),
'item_name' => $product->get_name(),
'price' => floatval($product->get_price()),
'quantity' => intval($cart_item['quantity']),
'category' => wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names'])[0] ?? '',
];
$context['cart_items'][] = $item_data;
$context['content_ids'][] = $product->get_id();
}
}
}
}
elseif (is_order_received_page()) {
// Страница благодарности - Purchase
$order_id = get_query_var('order-received');
if ($order_id) {
$order = wc_get_order($order_id);
if ($order && $order instanceof WC_Order) {
$context['pixel_event_type'] = 'Purchase';
$order_items = [];
$content_ids = [];
foreach ($order->get_items() as $item) {
if ($item instanceof WC_Order_Item_Product) {
$product = $item->get_product();
if ($product && $product instanceof WC_Product) {
$order_items[] = [
'item_id' => $product->get_id(),
'item_name' => $product->get_name(),
'price' => floatval($item->get_total() / $item->get_quantity()),
'quantity' => intval($item->get_quantity()),
'category' => wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names'])[0] ?? '',
];
$content_ids[] = $product->get_id();
}
}
}
$context['order'] = [
'id' => $order->get_id(),
'total' => floatval($order->get_total()),
'currency' => $order->get_currency(),
'items' => $order_items,
'content_ids' => $content_ids,
'order_key' => $order->get_order_key(),
];
}
}
}
else {
// Все остальные страницы - PageView + подготовка для AddToCart
$context['pixel_event_type'] = 'PageView';
$context['enable_addtocart'] = true; // Включаем обработчик AddToCart
// Дополнительные данные для PageView
global $wp_query;
$context['page_data'] = [
'page_title' => wp_get_document_title(),
'page_url' => home_url(add_query_arg(array(), $wp_query->request)),
'page_type' => get_page_type(),
];
}
// Рендерим шаблон
\Timber\Timber::render('templates/head-pixel-functions.twig', $context);
}
});