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

458 lines
19 KiB

<?php
/* Start | Работа с проверкой мультисайтовости и стендов */
class SiteEnvironment
{
public string $mode;
public string $region;
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'];
}
}
add_filter('timber/twig', function (\Twig\Environment $twig) {
$site_env = new SiteEnvironment();
$twig->addGlobal('site_region', $site_env->site_region);
$twig->addGlobal('site_mode', $site_env->site_mode);
return $twig;
});
/* End | Работа с проверкой мультисайтовости и стендов */
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;
}
add_filter('timber/context', function($context) {
// Передаем все нужные константы в контекст Twig
$context['CONSTANTS'] = [
'DOMAIN' => defined('SITE_DOMAIN') ? SITE_DOMAIN : null,
];
return $context;
});
// Отключаем канонические ссылки и hreflang от Yoast SEO
add_filter('wpseo_canonical', '__return_false');
add_filter('wpseo_opengraph_url', '__return_false'); // Отключаем OG URL
add_filter('wpseo_add_x_default_hreflang', '__return_false'); // Отключаем hreflang от Yoast
add_filter('wpseo_disable_adjacent_rel_links', '__return_true'); // Отключаем соседние rel-ссылки
// Добавляем каноническую ссылку
add_action('wp_head', 'custom_canonical_url', 5);
function custom_canonical_url() {
if (!is_admin()) {
// Защищаем от дублирования
static $canonical_added = false;
if ($canonical_added) {
return;
}
$canonical_added = true;
// Формируем текущий URL без лишних параметров
$current_url = trailingslashit(home_url($_SERVER['REQUEST_URI']));
// Удаляем возможные параметры запроса, если они не нужны
$current_url = strtok($current_url, '?');
echo '<link rel="canonical" href="' . esc_url($current_url) . '" />' . "\n";
}
}
add_action('wp_head', 'add_facebook_pixel');
function add_facebook_pixel() {
?>
<!-- Meta 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', '1791804684725971');
fbq('track', 'PageView');
</script>
<noscript>
<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=1791804684725971&ev=PageView&noscript=1"/>
</noscript>
<!-- End Meta Pixel Code -->
<?php
}
add_action('woocommerce_thankyou', 'send_purchase_to_metrika');
function send_purchase_to_metrika($order_id) {
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); ?>
});
// Facebook Pixel
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('wp_footer', 'add_facebook_pixel_events');
function add_facebook_pixel_events() {
// 1. Событие 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(); ?>'; // Динамическая валюта
// Событие для Facebook Pixel
fbq('track', 'AddToCart', {
content_ids: [productId],
content_type: 'product',
value: parseFloat(priceElement) * quantity,
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
}]
}
});
});
});
});
</script>
<?php
}
// 2. Событие 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
}
// 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.push({
'event': 'add_payment_info',
'ecommerce': {
'currency': '<?php echo $currency; ?>',
'value': <?php echo $cart_total; ?>
}
});
});
</script>
<?php
}
}
// Ваш код для custom_enqueue_ajax_add_to_cart остается без изменений
add_action('wp_enqueue_scripts', 'custom_enqueue_ajax_add_to_cart');
function custom_enqueue_ajax_add_to_cart() {
// Подключаем скрипт только на странице товара
if (is_product()) {
// Убедимся, что jQuery подключен
wp_enqueue_script('jquery');
// Inline JavaScript с поддержкой jQuery.noConflict
$ajax_script = "
jQuery(document).ready(function($) {
console.log('AJAX Add to Cart script loaded'); // Отладка: проверяем загрузку скрипта
// Перехват клика по кнопке
$('.single_add_to_cart_button').on('click', function(e) {
e.preventDefault();
e.stopPropagation(); // Предотвращаем всплытие события
console.log('Add to cart button clicked'); // Отладка: клик по кнопке
var \$button = $(this);
var \$form = \$button.closest('form.cart');
var product_id = \$button.val(); // Извлекаем product_id из value кнопки
var quantity = \$form.find('input[name=\"quantity\"]').val() || 1;
// Проверка на корректность product_id
if (!product_id || isNaN(product_id)) {
console.log('Invalid product_id:', product_id); // Отладка
console.log('Error: Неверный ID товара');
\$button.removeClass('loading').prop('disabled', false); // Разблокируем кнопку
return;
}
// Блокируем кнопку
\$button.addClass('loading').prop('disabled', true);
console.log('Sending AJAX request for product_id: ' + product_id + ', quantity: ' + quantity); // Отладка
// Подготовка данных
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: product_id,
quantity: quantity
};
// Добавляем поле url, если есть
var urlField = \$form.find('input[name=\"url\"]');
if (urlField.length) {
data.url = urlField.val();
}
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: data,
dataType: 'json',
success: function(response) {
console.log('AJAX response:', response); // Отладка
if (response.success) {
console.log('Товар добавлен в корзину'); // Уведомление в консоли
// Обновляем фрагменты корзины
if (response.data.fragments) {
$.each(response.data.fragments, function(key, value) {
console.log('Updating fragment:', key); // Отладка
$(key).replaceWith(value);
});
}
$(document.body).trigger('wc_fragment_refresh');
$(document.body).trigger('added_to_cart', [response.data.fragments, response.data.cart_hash]);
// Сбрасываем форму
\$form[0].reset();
console.log('Form reset after successful add to cart'); // Отладка
} else {
console.log('Error: ' + (response.data.message || 'Ошибка при добавлении товара в корзину')); // Уведомление в консоли
}
},
error: function(xhr, status, error) {
console.error('AJAX error:', status, error); // Отладка
console.log('Error: Произошла ошибка при добавлении товара: ' + error);
},
complete: function() {
console.log('AJAX request completed'); // Отладка
\$button.removeClass('loading').prop('disabled', false); // Разблокируем кнопку
}
});
});
// Перехват отправки формы
$('form.cart').on('submit', function(e) {
e.preventDefault();
e.stopPropagation(); // Предотвращаем всплытие
console.log('Form submit prevented'); // Отладка
});
});
";
wp_add_inline_script('jquery', $ajax_script);
// Передаем AJAX URL
wp_localize_script('jquery', 'ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php')
));
// Inline CSS
wp_enqueue_style('woocommerce-custom-styles', get_template_directory_uri() . '/style.css', array(), '1.0');
$custom_css = "
.single_add_to_cart_button.loading {
opacity: 0.5;
cursor: not-allowed;
position: relative;
}
.single_add_to_cart_button.loading:after {
content: '';
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #fff;
border-radius: 50%;
border-top-color: transparent;
animation: spin 1s linear infinite;
position: absolute;
right: 10px;
}
@keyframes spin {
100% {
transform: rotate(360deg);
}
}
";
wp_add_inline_style('woocommerce-custom-styles', $custom_css);
}
}
// Отключаем кэширование для страниц товаров
add_action('template_redirect', function() {
if (is_product()) {
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
}
});
add_action('wp_head', 'custom_hreflang_shop', 6);
function custom_hreflang_shop() {
if (!is_admin() && function_exists('pll_get_post') && function_exists('pll_languages_list')) {
// Защищаем от дублирования
static $hreflang_added = false;
if ($hreflang_added) {
return;
}
$hreflang_added = true;
// Домены для языков
$ru_domain = 'https://cosmopet-test-ru.cp.good-production.xyz';
$en_domain = 'https://cosmopet-test-ae.cp.good-production.xyz';
// Текущий пост/страница
$current_post_id = get_the_ID();
if (!$current_post_id) {
// Для случаев, когда get_the_ID() не работает (например, архивы)
$current_path = trailingslashit($_SERVER['REQUEST_URI']);
$query_string = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
$ru_url = $ru_domain . $current_path . $query_string;
$en_url = $en_domain . $current_path . $query_string;
} else {
// Получаем переводы поста/страницы
$ru_post_id = pll_get_post($current_post_id, 'ru');
$en_post_id = pll_get_post($current_post_id, 'en');
// Формируем URL с учетом перевода и параметров запроса
$query_string = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
$ru_url = $ru_post_id ? get_permalink($ru_post_id) . $query_string : $ru_domain . trailingslashit($_SERVER['REQUEST_URI']) . $query_string;
$en_url = $en_post_id ? get_permalink($en_post_id) . $query_string : $en_domain . trailingslashit($_SERVER['REQUEST_URI']) . $query_string;
}
// Выводим hreflang-теги
echo '<link rel="alternate" hreflang="ru-RU" href="' . esc_url($ru_url) . '" />' . "\n";
echo '<link rel="alternate" hreflang="en-AE" href="' . esc_url($en_url) . '" />' . "\n";
}
}