Maks | formating files and add TO_DO

pull/36/head
Антон 1 month ago
parent 3c41995cb6
commit e3f48095fb
  1. 191
      wp-content/themes/cosmopet/global-functions/multisite-functions.php
  2. 191
      wp-content/themes/cosmopet/modules/footer/assets/js/footer.js

@ -87,112 +87,110 @@ if($site_env->site_mode == 'production' and $site_env->site_region == 'ae') {
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 // Событие для 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
});
// Событие для Google Analytics
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
}]
}
});
}); });
// Событие для Google Analytics
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> </script>
<?php <? }
}
// 2. Событие Purchase (Покупка)
// 2. Событие 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 = window.dataLayer || [];
window.dataLayer.push({ window.dataLayer.push({
'event': 'purchase', 'event': 'purchase',
'ecommerce': { 'ecommerce': {
'currency': '<?php echo $order->get_currency(); ?>', 'currency': '<?php echo $order->get_currency(); ?>',
'value': <?php echo $order->get_total(); ?>, 'value': <?php echo $order->get_total(); ?>,
'items': <?php echo json_encode($items); ?> 'items': <?php echo json_encode($items); ?>
} }
});
}); });
}); </script>
</script> <?php
<?php }
}
// 3. Событие AddPaymentInfo // 3. Событие AddPaymentInfo
if (is_checkout() && !is_wc_endpoint_url('order-received')) { if (is_checkout() && !is_wc_endpoint_url('order-received')) {
$currency = get_woocommerce_currency(); $currency = get_woocommerce_currency();
$cart_total = WC()->cart ? WC()->cart->get_total('edit') : 0; $cart_total = WC()->cart ? WC()->cart->get_total('edit') : 0;
?> ?>
<script> <script>
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'AddPaymentInfo', { fbq('track', 'AddPaymentInfo', {
value: <?php echo $cart_total; ?>, value: <?php echo $cart_total; ?>,
currency: '<?php echo $currency; ?>' currency: '<?php echo $currency; ?>'
}); });
window.dataLayer = window.dataLayer || []; window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ window.dataLayer.push({
'event': 'add_payment_info', 'event': 'add_payment_info',
'ecommerce': { 'ecommerce': {
'currency': '<?php echo $currency; ?>', 'currency': '<?php echo $currency; ?>',
'value': <?php echo $cart_total; ?> 'value': <?php echo $cart_total; ?>
} }
});
}); });
}); </script>
</script> <? }
<?php
}
} }
/* Передача контрибуции со страницы "Спасибо" */ /* Передача контрибуции со страницы "Спасибо" */
@ -255,6 +253,7 @@ if($site_env->site_mode == 'production' and $site_env->site_region == 'ae') {
} }
} }
// TO_DO: удалить, если не нужно
// Отключаем кэширование для страниц товаров // Отключаем кэширование для страниц товаров
add_action('template_redirect', function() { add_action('template_redirect', function() {
if (is_product()) { if (is_product()) {

@ -7,34 +7,35 @@
// Флаг для предотвращения множественной обработки // Флаг для предотвращения множественной обработки
let isProcessing = false; let isProcessing = false;
// TO_DO : вынести логику в модуль авторизации/регистрации
// Login // Login
$('.login_popup').on('click', function(e){ $('.login_popup').on('click', function (e) {
e.preventDefault(); e.preventDefault();
$('.login_modal').addClass('active'); $('.login_modal').addClass('active');
}); });
$('.login_close').on('click', function(){ $('.login_close').on('click', function () {
$('.login_modal').removeClass('active'); $('.login_modal').removeClass('active');
$('.login_forms').removeClass('hide'); $('.login_forms').removeClass('hide');
$('.login_success').addClass('hide'); $('.login_success').addClass('hide');
$('.login_auth').addClass('hide'); $('.login_auth').addClass('hide');
isProcessing = false; // Сбрасываем флаг при закрытии isProcessing = false; // Сбрасываем флаг при закрытии
}); });
$('.login_back').on('click', function(){ $('.login_back').on('click', function () {
if($(this).is('.disabled')) { if ($(this).is('.disabled')) {
return false; return false;
} }
$('.login_wrap .step').toggleClass('active'); $('.login_wrap .step').toggleClass('active');
}); });
$('.login_input input').on('input keyup', function(){ $('.login_input input').on('input keyup', function () {
$('.login_input').removeClass('error'); $('.login_input').removeClass('error');
}); });
$('.js-get-code').on('click', function(){ $('.js-get-code').on('click', function () {
$('.login_input').removeClass('error'); $('.login_input').removeClass('error');
var email = $('.js-input-email input').val(); var email = $('.js-input-email input').val();
$('.sended_email').text(email); $('.sended_email').text(email);
if(email === '') { if (email === '') {
$('.js-input-email').addClass('error'); $('.js-input-email').addClass('error');
$('.js-input-email .login_error').text(localeValue == 'en_US' ? 'Enter your email' : 'Укажите Email'); $('.js-input-email .login_error').text(localeValue == 'en_US' ? 'Enter your email' : 'Укажите Email');
return false; return false;
@ -43,9 +44,9 @@
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '/wp-admin/admin-ajax.php', url: '/wp-admin/admin-ajax.php',
data: {action: 'email_validate', email:email}, data: { action: 'email_validate', email: email },
success: function(data){ success: function (data) {
if(data['status'] === 'error') { if (data['status'] === 'error') {
$('.js-input-email').addClass('error'); $('.js-input-email').addClass('error');
$('.js-input-email .login_error').text(data['text']); $('.js-input-email .login_error').text(data['text']);
return false; return false;
@ -57,63 +58,63 @@
}); });
} }
}); });
$('.js-repeat-code').on('click', function(){ $('.js-repeat-code').on('click', function () {
$('.login_input').removeClass('error'); $('.login_input').removeClass('error');
send_code(); send_code();
}); });
function send_code(){ function send_code() {
$('.login_timer').show(); $('.login_timer').show();
$('.js-repeat-code').hide(); $('.js-repeat-code').hide();
$('.login_back').addClass('disabled'); $('.login_back').addClass('disabled');
// Timer // Timer
var seconds = 15; var seconds = 15;
var interval = setInterval(function() { var interval = setInterval(function () {
if (seconds > 0) { if (seconds > 0) {
seconds--; seconds--;
$('.seconds').text(seconds); $('.seconds').text(seconds);
} else { } else {
clearInterval(interval); clearInterval(interval);
$('.login_timer').hide(); $('.login_timer').hide();
$('.js-repeat-code').show(); $('.js-repeat-code').show();
$('.login_back').removeClass('disabled'); $('.login_back').removeClass('disabled');
$('.seconds').text(15); $('.seconds').text(15);
} }
}, 1000); }, 1000);
// Ajax отправка кода // Ajax отправка кода
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '/wp-admin/admin-ajax.php', url: '/wp-admin/admin-ajax.php',
data: {action: 'send_code', email: $('.js-input-email input').val()} data: { action: 'send_code', email: $('.js-input-email input').val() }
}); });
} }
// Проверка кода и регистрация/авторизация // Проверка кода и регистрация/авторизация
$('.js-input-code input').on('input keydown keyup propertychange paste cut copy change', function(){ $('.js-input-code input').on('input keydown keyup propertychange paste cut copy change', function () {
var val = $(this).val(); var val = $(this).val();
var email = $('.js-input-email input').val(); var email = $('.js-input-email input').val();
if(val.length === 4 && !isProcessing) { if (val.length === 4 && !isProcessing) {
isProcessing = true; // Устанавливаем флаг, чтобы предотвратить повторную обработку isProcessing = true; // Устанавливаем флаг, чтобы предотвратить повторную обработку
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '/wp-admin/admin-ajax.php', url: '/wp-admin/admin-ajax.php',
data: {action: 'check_code', code: val, email: email}, data: { action: 'check_code', code: val, email: email },
success: function(data){ success: function (data) {
console.log('Server response:', data); // Отладка ответа сервера console.log('Server response:', data); // Отладка ответа сервера
if(data['status'] === 'success_reg') { if (data['status'] === 'success_reg') {
$('.login_forms').addClass('hide'); $('.login_forms').addClass('hide');
$('.login_success').removeClass('hide'); $('.login_success').removeClass('hide');
$('.login_auth').addClass('hide'); // Гарантируем, что login_auth скрыт $('.login_auth').addClass('hide'); // Гарантируем, что login_auth скрыт
if (typeof wc_checkout_params !== 'undefined') { if (typeof wc_checkout_params !== 'undefined') {
location.reload(); location.reload();
} }
} else if(data['status'] === 'success_auth' && !$('.login_success').is(':visible')) { } else if (data['status'] === 'success_auth' && !$('.login_success').is(':visible')) {
$('.login_forms').addClass('hide'); $('.login_forms').addClass('hide');
$('.login_auth').removeClass('hide'); $('.login_auth').removeClass('hide');
$('.login_success').addClass('hide'); // Гарантируем, что login_success скрыт $('.login_success').addClass('hide'); // Гарантируем, что login_success скрыт
if (typeof wc_checkout_params !== 'undefined') { if (typeof wc_checkout_params !== 'undefined') {
location.reload(); location.reload();
} }
} else if(data['status'] === 'error') { } else if (data['status'] === 'error') {
$('.js-input-code').addClass('error'); $('.js-input-code').addClass('error');
$('.js-input-code .login_error').text(data['text']); $('.js-input-code .login_error').text(data['text']);
isProcessing = false; // Сбрасываем флаг при ошибке isProcessing = false; // Сбрасываем флаг при ошибке
@ -124,7 +125,7 @@
isProcessing = false; // Сбрасываем флаг при неожиданном статусе isProcessing = false; // Сбрасываем флаг при неожиданном статусе
} }
}, },
error: function(xhr, status, error) { error: function (xhr, status, error) {
console.error('AJAX error:', error); // Отладка ошибок AJAX console.error('AJAX error:', error); // Отладка ошибок AJAX
$('.js-input-code').addClass('error'); $('.js-input-code').addClass('error');
$('.js-input-code .login_error').text(localeValue == 'en_US' ? 'Server error' : 'Ошибка сервера'); $('.js-input-code .login_error').text(localeValue == 'en_US' ? 'Server error' : 'Ошибка сервера');
@ -134,7 +135,7 @@
} }
}); });
$('.email_link_form').on('submit', function(e){ $('.email_link_form').on('submit', function (e) {
e.preventDefault(); e.preventDefault();
$('.cabinet-card_linked-email .error').remove(); $('.cabinet-card_linked-email .error').remove();
var data = $(this).serializeArray(); var data = $(this).serializeArray();
@ -142,9 +143,9 @@
type: 'POST', type: 'POST',
url: '/wp-admin/admin-ajax.php', url: '/wp-admin/admin-ajax.php',
data: data, data: data,
success: function(data){ success: function (data) {
if(data['error']) { if (data['error']) {
$('.cabinet-card_linked-email').append('<div class="cabinet-card__status cabinet-card__status--cancelled error">'+data['error']+'</div>'); $('.cabinet-card_linked-email').append('<div class="cabinet-card__status cabinet-card__status--cancelled error">' + data['error'] + '</div>');
} else { } else {
location.reload(); location.reload();
} }
@ -160,89 +161,89 @@ function checkImage(imageSrc, good) {
} }
// header // header
toggleOpenX('.lang', '.lang__open', '.lang__list', '.lang__content', false); toggleOpenX('.lang', '.lang__open', '.lang__list', '.lang__content', false);
toggleHeader('#pc-menu','.header__menu-block','.header__pc-menu', '.white', 'white'); toggleHeader('#pc-menu', '.header__menu-block', '.header__pc-menu', '.white', 'white');
toggleHeader('#phone-menu','.header__menu-block','.header__phone-menu', '.white', 'white'); toggleHeader('#phone-menu', '.header__menu-block', '.header__phone-menu', '.white', 'white');
// header // header
function initOverlay(){ function initOverlay() {
// overlay // overlay
let products = document.querySelectorAll('.product__item'); let products = document.querySelectorAll('.product__item');
products.forEach(productItem => { products.forEach(productItem => {
let button = productItem.querySelector('.open-overlay'), let button = productItem.querySelector('.open-overlay'),
overlay = productItem.querySelector('.product-item__overlay'); overlay = productItem.querySelector('.product-item__overlay');
if (button) { if (button) {
button.onclick = function (e) { button.onclick = function (e) {
document.querySelectorAll('.product__item').forEach(e => { document.querySelectorAll('.product__item').forEach(e => {
if (e.classList.contains('active')) { if (e.classList.contains('active')) {
e.classList.remove('active'); e.classList.remove('active');
} }
}); });
document.querySelectorAll('.product-item__overlay').forEach(e => { document.querySelectorAll('.product-item__overlay').forEach(e => {
if (e.classList.contains('active')) { if (e.classList.contains('active')) {
e.classList.remove('active'); e.classList.remove('active');
} }
}); });
productItem.classList.toggle('active'); productItem.classList.toggle('active');
overlay.classList.toggle('active'); overlay.classList.toggle('active');
}
} }
}
}) })
// overlay // overlay
} }
initOverlay() initOverlay()
function initSelect(){ function initSelect() {
// select // select
toggleOpenX('.select', '.select__state' , '.state__content', '.state__block', true); toggleOpenX('.select', '.select__state', '.state__content', '.state__block', true);
let selects = document.querySelectorAll('.select'); let selects = document.querySelectorAll('.select');
selects.forEach(select => { selects.forEach(select => {
let state = select.querySelector('.select__state'), let state = select.querySelector('.select__state'),
content = select.querySelector('.state__block'), content = select.querySelector('.state__block'),
buttons = select.querySelectorAll('.state__button'); buttons = select.querySelectorAll('.state__button');
buttons.forEach(e => { buttons.forEach(e => {
let button = e; let button = e;
e.onclick = function (event) { e.onclick = function (event) {
event.preventDefault(); event.preventDefault();
buttons.forEach(element => { buttons.forEach(element => {
if (element.classList.contains('active')) { if (element.classList.contains('active')) {
element.classList.remove('active'); element.classList.remove('active');
} }
}) })
let text = e.textContent.trim(); let text = e.textContent.trim();
state.value = text; state.value = text;
button.classList.add('active'); button.classList.add('active');
content.style.height = 0; content.style.height = 0;
select.classList.remove('active'); select.classList.remove('active');
} }
})
}) })
})
// select // select
} }
initSelect() initSelect()
function toggleOpenX(mainElement, buttonElement ,heightElement, contentElement, close) { function toggleOpenX(mainElement, buttonElement, heightElement, contentElement, close) {
let elements = document.querySelectorAll(mainElement); let elements = document.querySelectorAll(mainElement);
elements.forEach(e => { elements.forEach(e => {
@ -266,7 +267,7 @@ function toggleOpenX(mainElement, buttonElement ,heightElement, contentElement,
if (!thisMainElement.classList.contains('active')) { if (!thisMainElement.classList.contains('active')) {
thisContentElement.style.height = `${height}px`; thisContentElement.style.height = `${height}px`;
thisMainElement.classList.add('active'); thisMainElement.classList.add('active');
}else{ } else {
thisContentElement.style.height = null; thisContentElement.style.height = null;
thisMainElement.classList.remove('active'); thisMainElement.classList.remove('active');
} }
@ -286,12 +287,12 @@ function toggleHeader(button, content, blockheight, removeBlock, removeClass) {
if (!thisContent.classList.contains('open')) { if (!thisContent.classList.contains('open')) {
thisContent.style.height = `${height}px`; thisContent.style.height = `${height}px`;
thisContent.classList .add('open'); thisContent.classList.add('open');
if (removeBlock) { if (removeBlock) {
thisRemoveBlock.classList.remove(removeClass); thisRemoveBlock.classList.remove(removeClass);
} }
}else{ } else {
thisContent.style.height = null; thisContent.style.height = null;
thisContent.classList.remove('open'); thisContent.classList.remove('open');
@ -309,15 +310,15 @@ if (document.querySelector('.header').classList.contains('white')) {
window.addEventListener("scroll", function (e) { window.addEventListener("scroll", function (e) {
let header = document.querySelector('.header'); let header = document.querySelector('.header');
let scroll = window.scrollY; let scroll = window.scrollY;
if(!menu_opened){ if (!menu_opened) {
if (scroll >= 25) { if (scroll >= 25) {
header.classList.remove('white') header.classList.remove('white')
}else{ } else {
header.classList.add('white') header.classList.add('white')
}
} }
}
}); });
} }

Loading…
Cancel
Save