From 6e2a763cb7e20f658bfa5b9eac559666651922a4 Mon Sep 17 00:00:00 2001 From: maksim Date: Tue, 5 Aug 2025 11:15:17 +0300 Subject: [PATCH] =?UTF-8?q?Andrei=20|=20=D0=B7=D0=B0=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=81=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BB=20=D0=B8=D0=B7=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE=20=D1=80?= =?UTF-8?q?=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../global-functions/metrics-functions.php | 380 +++++++++++++++++ .../global-functions/multilang-functions.php | 88 ++-- .../global-functions/multisite-functions.php | 389 +----------------- .../global-functions/seo-functions.php | 18 + wp-content/themes/cosmopet/page.php | 1 + .../cosmopet/temp-functions/ajax-logic.php | 23 +- .../temp-functions/woocommerce-logic.php | 3 + .../templates/profile/profile-orders.twig | 11 - .../cosmopet/templates/profile/profile.twig | 15 +- .../templates/shop/product-card_element.twig | 9 + .../woocommerce/checkout/form-coupon.php | 3 + .../woocommerce/checkout/form-shipping.php | 2 + .../woocommerce/checkout/order-receipt.php | 2 + .../woocommerce/checkout/review-order.php | 2 + 14 files changed, 479 insertions(+), 467 deletions(-) create mode 100644 wp-content/themes/cosmopet/global-functions/metrics-functions.php create mode 100644 wp-content/themes/cosmopet/global-functions/seo-functions.php diff --git a/wp-content/themes/cosmopet/global-functions/metrics-functions.php b/wp-content/themes/cosmopet/global-functions/metrics-functions.php new file mode 100644 index 0000000..088ab66 --- /dev/null +++ b/wp-content/themes/cosmopet/global-functions/metrics-functions.php @@ -0,0 +1,380 @@ +site_mode == 'production' && $site_env->site_region == 'ae') { + + // Проверка на тестовый режим для метрик + // TO_DO: дуюлирует логику is_gp_test_mode в wp-content/themes/cosmopet/global-functions/multisite-functions.php + 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) { + ?> + + cart && WC()->cart->get_cart_contents_count() > 0) { + ?> + + + + cart && WC()->cart->get_cart_contents_count() > 0) { + $currency = get_woocommerce_currency(); + $cart_total = WC()->cart->get_total('edit'); + ?> + + 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() + ]; + } + ?> + + 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(); + ?> + + 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); + } +}); + + +function get_page_type() +{ + if (is_home() || is_front_page()) { + return 'home'; + } elseif (is_shop()) { + return 'shop'; + } elseif (is_product_category()) { + return 'category'; + } elseif (is_product_tag()) { + return 'tag'; + } elseif (is_search()) { + return 'search'; + } elseif (is_cart()) { + return 'cart'; + } elseif (is_account_page()) { + return 'account'; + } else { + return 'other'; + } +} diff --git a/wp-content/themes/cosmopet/global-functions/multilang-functions.php b/wp-content/themes/cosmopet/global-functions/multilang-functions.php index b30f38c..6772501 100644 --- a/wp-content/themes/cosmopet/global-functions/multilang-functions.php +++ b/wp-content/themes/cosmopet/global-functions/multilang-functions.php @@ -1842,50 +1842,50 @@ pll_register_string('This item is not on our website yet, but it will be here ve add_action('wp_head', function () { if (function_exists('pll_current_language')) { $lang = pll_current_language(); -$translations = [ - 'en' => [ - 'name_required' => 'The name is required.', - 'email_invalid' => 'Email is incorrect.', - 'phone_invalid' => 'The phone number is incorrect.', - 'error_coupon_empty' => 'Please enter the coupon code.', - 'error_coupon_invalid' => 'Error! The coupon code is invalid or does not exist.', - 'error_generic' => 'An error occurred. Please try again.', - 'shipping_method_error' => 'No pickup point selected for delivery.', - 'shipping_address_error' => 'Delivery address not provided', - 'email_taken_error' => 'This email is already registered. Please log in or provide a different email.', - 'phone_number_error' => 'Incorrect phone number entered.', - 'shipping_method_missing' => 'No delivery method selected. Please check your address or contact the site administration for help.', - 'change_address' => 'Change address', - 'shipping_updated' => 'Shipping methods will be updated during checkout.', - 'coupon_applied' => 'Coupon applied: ', - - // 🔽 Новые строки из JS - 'Choose pick-up' => 'Choose pick-up', - 'Re-select pick-up' => 'Re-select pick-up', - 'There are no CDEK pick-up points available in this direction, please select another delivery method' => - 'There are no CDEK pick-up points available in this direction, please select another delivery method' - ], - 'ru' => [ - 'name_required' => 'Поле имени обязательно для заполнения.', - 'email_invalid' => 'Введите корректный email.', - 'phone_invalid' => 'Введите корректный номер телефона.', - 'error_coupon_empty' => 'Пожалуйста, введите код купона.', - 'error_coupon_invalid' => 'Ошибка! Промокод введен неверно или не существует.', - 'error_generic' => 'Произошла ошибка. Попробуйте ещё раз.', - 'shipping_method_error' => 'Не выбран ПВЗ для доставки заказа.', - 'shipping_address_error' => 'Не указан адрес доставки', - 'email_taken_error' => 'Этот email уже зарегистрирован. Войдите в свой аккаунт или укажите другой E-mail.', - 'phone_number_error' => 'Неправильно введен номер', - 'shipping_method_missing' => 'Не выбран метод доставки. Пожалуйста перепроверьте ваш адрес или обратитесь за помощью к администрации сайта.', - 'change_address' => 'Изменить адрес', - 'shipping_updated' => 'Методы доставки будут обновлены в процессе оформления заказа.', - 'coupon_applied' => 'Применен промокод: ', - 'Choose pick-up' => 'Выбрать пункт выдачи', - 'Re-select pick-up' => 'Выбрать другой пункт выдачи', - 'There are no CDEK pick-up points available in this direction, please select another delivery method' => - 'В этом направлении нет доступных пунктов выдачи CDEK, пожалуйста, выберите другой способ доставки' - ] -]; + $translations = [ + 'en' => [ + 'name_required' => 'The name is required.', + 'email_invalid' => 'Email is incorrect.', + 'phone_invalid' => 'The phone number is incorrect.', + 'error_coupon_empty' => 'Please enter the coupon code.', + 'error_coupon_invalid' => 'Error! The coupon code is invalid or does not exist.', + 'error_generic' => 'An error occurred. Please try again.', + 'shipping_method_error' => 'No pickup point selected for delivery.', + 'shipping_address_error' => 'Delivery address not provided', + 'email_taken_error' => 'This email is already registered. Please log in or provide a different email.', + 'phone_number_error' => 'Incorrect phone number entered.', + 'shipping_method_missing' => 'No delivery method selected. Please check your address or contact the site administration for help.', + 'change_address' => 'Change address', + 'shipping_updated' => 'Shipping methods will be updated during checkout.', + 'coupon_applied' => 'Coupon applied: ', + + // 🔽 Новые строки из JS + 'Choose pick-up' => 'Choose pick-up', + 'Re-select pick-up' => 'Re-select pick-up', + 'There are no CDEK pick-up points available in this direction, please select another delivery method' => + 'There are no CDEK pick-up points available in this direction, please select another delivery method' + ], + 'ru' => [ + 'name_required' => 'Поле имени обязательно для заполнения.', + 'email_invalid' => 'Введите корректный email.', + 'phone_invalid' => 'Введите корректный номер телефона.', + 'error_coupon_empty' => 'Пожалуйста, введите код купона.', + 'error_coupon_invalid' => 'Ошибка! Промокод введен неверно или не существует.', + 'error_generic' => 'Произошла ошибка. Попробуйте ещё раз.', + 'shipping_method_error' => 'Не выбран ПВЗ для доставки заказа.', + 'shipping_address_error' => 'Не указан адрес доставки', + 'email_taken_error' => 'Этот email уже зарегистрирован. Войдите в свой аккаунт или укажите другой E-mail.', + 'phone_number_error' => 'Неправильно введен номер', + 'shipping_method_missing' => 'Не выбран метод доставки. Пожалуйста перепроверьте ваш адрес или обратитесь за помощью к администрации сайта.', + 'change_address' => 'Изменить адрес', + 'shipping_updated' => 'Методы доставки будут обновлены в процессе оформления заказа.', + 'coupon_applied' => 'Применен промокод: ', + 'Choose pick-up' => 'Выбрать пункт выдачи', + 'Re-select pick-up' => 'Выбрать другой пункт выдачи', + 'There are no CDEK pick-up points available in this direction, please select another delivery method' => + 'В этом направлении нет доступных пунктов выдачи CDEK, пожалуйста, выберите другой способ доставки' + ] + ]; diff --git a/wp-content/themes/cosmopet/global-functions/multisite-functions.php b/wp-content/themes/cosmopet/global-functions/multisite-functions.php index 72f6d82..8e96018 100644 --- a/wp-content/themes/cosmopet/global-functions/multisite-functions.php +++ b/wp-content/themes/cosmopet/global-functions/multisite-functions.php @@ -35,391 +35,4 @@ add_filter('timber/twig', function (\Twig\Environment $twig) { 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 '' . "\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) { - ?> - - cart && WC()->cart->get_cart_contents_count() > 0) { - ?> - - - - cart && WC()->cart->get_cart_contents_count() > 0) { - $currency = get_woocommerce_currency(); - $cart_total = WC()->cart->get_total('edit'); - ?> - - 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() - ]; - } - ?> - - 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(); - ?> - - 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); - } -}); - - -function get_page_type() { - if (is_home() || is_front_page()) { - return 'home'; - } elseif (is_shop()) { - return 'shop'; - } elseif (is_product_category()) { - return 'category'; - } elseif (is_product_tag()) { - return 'tag'; - } elseif (is_search()) { - return 'search'; - } elseif (is_cart()) { - return 'cart'; - } elseif (is_account_page()) { - return 'account'; - } else { - return 'other'; - } -} +}, 10, 2); \ No newline at end of file diff --git a/wp-content/themes/cosmopet/global-functions/seo-functions.php b/wp-content/themes/cosmopet/global-functions/seo-functions.php new file mode 100644 index 0000000..d639be1 --- /dev/null +++ b/wp-content/themes/cosmopet/global-functions/seo-functions.php @@ -0,0 +1,18 @@ +' . "\n"; + } +}); \ No newline at end of file diff --git a/wp-content/themes/cosmopet/page.php b/wp-content/themes/cosmopet/page.php index 968f7cd..49cbf5e 100644 --- a/wp-content/themes/cosmopet/page.php +++ b/wp-content/themes/cosmopet/page.php @@ -5,6 +5,7 @@ * This is the template that renders pages using Timber (Twig). */ +/* TO_DO сюда перенести логику home.php */ if (is_account_page() && !is_wc_endpoint_url()){ include_module('profile'); diff --git a/wp-content/themes/cosmopet/temp-functions/ajax-logic.php b/wp-content/themes/cosmopet/temp-functions/ajax-logic.php index dbba447..568f487 100644 --- a/wp-content/themes/cosmopet/temp-functions/ajax-logic.php +++ b/wp-content/themes/cosmopet/temp-functions/ajax-logic.php @@ -1,5 +1,8 @@ - {% include 'profile/order-list.twig' %} diff --git a/wp-content/themes/cosmopet/templates/profile/profile.twig b/wp-content/themes/cosmopet/templates/profile/profile.twig index 3d1de51..4744dc0 100644 --- a/wp-content/themes/cosmopet/templates/profile/profile.twig +++ b/wp-content/themes/cosmopet/templates/profile/profile.twig @@ -4,24 +4,11 @@ {% block profile_content%}
- {% include 'profile/order-list.twig' %}
- - - +{# TO_DO нужен ли тут
? #} {% endblock %} diff --git a/wp-content/themes/cosmopet/templates/shop/product-card_element.twig b/wp-content/themes/cosmopet/templates/shop/product-card_element.twig index d4e9c52..0133743 100644 --- a/wp-content/themes/cosmopet/templates/shop/product-card_element.twig +++ b/wp-content/themes/cosmopet/templates/shop/product-card_element.twig @@ -1,3 +1,12 @@ +{# TO_DO: + + 1) в контроллер вынести получение всех переменных, а не тут выхывать функции fn() + 2) переименовать в файл /shop/product-card.twig + 3) _product, wc_product, s_product -- не понятно почему множество переменных с одинаковым смыслом => + надо сделать единый контенкст для всех контроллеров и там создать все нужные переменные + +#} + {% set thumbnail = _product.get_image_id() ? function('wp_get_attachment_image_url', _product.get_image_id(), 'medium') : function('wc_placeholder_img_src') %} {% set images = _product.get_gallery_image_ids() %} {% set compound = fn('wc_get_product_terms', _product.get_id(), 'pa_compound') %} diff --git a/wp-content/themes/cosmopet/woocommerce/checkout/form-coupon.php b/wp-content/themes/cosmopet/woocommerce/checkout/form-coupon.php index 96635b9..34786ba 100644 --- a/wp-content/themes/cosmopet/woocommerce/checkout/form-coupon.php +++ b/wp-content/themes/cosmopet/woocommerce/checkout/form-coupon.php @@ -1,4 +1,7 @@