для Contact Form 7 */ function custom_add_form_tag_img_handler( $tag ) { return ''; } function custom_add_form_tag_img() { wpcf7_add_form_tag( 'img', 'custom_add_form_tag_img_handler' ); } add_action( 'wpcf7_init', 'custom_add_form_tag_img' ); add_action( 'wpcf7_before_send_mail', function( $contact_form, &$abort, $submission ) { $form_id = WPCF7_ContactForm::get_current(); if ($form_id->id == 17302) { $sub = $submission->get_posted_data( 'subscriber' ); $url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=PolzovatelyaSSajtaStatForma'; $data = array( "email" => $sub, "subscriptions" => array( array( "pointOfContact"=> "Email" ), ), ); $data_string = json_encode(array("customer" =>$data)); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); } }, 10, 3 ); add_action( 'wp_ajax_subform', 'subform_callback' ); add_action( 'wp_ajax_nopriv_subform', 'subform_callback' ); function subform_callback(){ $url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=DobavleniePolzovatelyaSSajta'; $data = array( "email" => $_POST['email'], "name" => $_POST['name'], "subscriptions" => array( array( "pointOfContact"=> "Email" ), ), ); $data_string = json_encode(array("customer" =>$data)); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); echo $result; wp_die(); } add_action( 'wp_ajax_message', 'message_callback' ); add_action( 'wp_ajax_nopriv_message', 'message_callback' ); function message_callback(){ $phone = $_POST['phone']; $name = $_POST['name']; $email = $_POST['email']; $msg = $_POST['msg']; $message = 'Имя - ' . $name . ' email - ' . $email . ' phone - ' . $phone . ' сообщение - ' . $msg; $headers = array( 'From: Cosmopet ', 'content-type: text/html; charset=utf-8', ); wp_mail('partners@cosmopet.ae', 'Сообщение с сайта Cosmopet', $message, $headers); wp_die(); } add_action( 'wp_ajax_product_subform', 'product_subform_callback' ); add_action( 'wp_ajax_nopriv_product_subform', 'product_subform_callback' ); function product_subform_callback(){ $dateTimeString = gmdate('Y-m-d H:i:s'); $sub = $_POST['email']; $url = 'https://api.mindbox.ru/v3/operations/sync?endpointId=cosmopet.Website&operation=UnauthUserDataGet'; $data = array( "email" => $sub, ); $data_string = json_encode(array("customer" =>$data)); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = json_decode(curl_exec($ch)); curl_close($ch); if ($result->customer->customFields->productInStock){ $current_subs = $result->customer->customFields->productInStock; $current_subs[] = $_POST['product_name']; $url = 'https://api.mindbox.ru/v3/operations/sync?endpointId=cosmopet.Website&operation=UserDataEdit'; $data = array( "email" => $sub, 'customFields' => array( "productInStock" => $current_subs, ), ); $data_string = json_encode(array("customer" =>$data)); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = json_decode(curl_exec($ch)); curl_close($ch); } else{ $url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=DobavleniePolzovatelyaSSajta'; $data = array( "email" => $sub, "subscriptions" => array( array( "pointOfContact"=> "Email" ), ), 'customFields' => array( "productInStock" => array( $_POST['product_name'], ), ), ); $data_string = json_encode(array("customer" =>$data)); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = json_decode(curl_exec($ch)); curl_close($ch); } wp_die(); } add_action( 'wp_ajax_subscription_sub__profile', 'subscription_sub__profile' ); add_action( 'wp_ajax_nopriv_subscription_sub__profile', 'subscription_sub__profile' ); function subscription_sub__profile(){ $url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=DobavleniePolzovatelyaSSajta'; $data = array( "email" => $_POST['email'], "subscriptions" => array( array( "pointOfContact"=> "Email" ), ), 'customFields' => array( "foodSub" => true, ), ); $data_string = json_encode(array("customer" =>$data)); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = json_decode(curl_exec($ch)); curl_close($ch); wp_die(); } //Не отправляем письма на почту через WPCF // function my_skip_mail($skip_mail, $contact_form) { // if($site_work_mode != 'production'){ // $skip_mail = true; // true skips sending the email // } // return $skip_mail; // } add_filter( 'wpcf7_skip_mail','my_skip_mail', PHP_INT_MAX, 2 ); add_action('init', function(){ register_post_type('smi', array( 'labels' => array( 'name' => 'СМИ о нас', ), 'public' => false, 'supports' => array('title', 'thumbnail'), 'show_ui' => true, 'has_archive' => false, )); }); add_filter('pll_get_post_types', 'add_cpt_to_pll', 10, 2); function add_cpt_to_pll($post_types, $hide) { if ($hide) // hides 'my_cpt' from the list of custom post types in Polylang settings unset($post_types['smi']); else // enables language and translation management for 'my_cpt' $post_types['smi'] = 'smi'; $post_types['wpcf7'] = 'wpcf7'; return $post_types; } // add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query' ); // function custom_woocommerce_product_query ($q) { // $q->set( 'post_type', array( 'product', 'product_variation' ) ); // return $q; // } add_action('wp_ajax_woocommerce_ajax_upd_cart_contents', 'woocommerce_ajax_upd_cart_contents'); add_action('wp_ajax_nopriv_woocommerce_ajax_upd_cart_contents', 'woocommerce_ajax_upd_cart_contents'); function woocommerce_ajax_upd_cart_contents() { ob_start(); get_cart_template(); // записываем всё, что в буфере, в переменную $html_cart = ob_get_contents(); // очищаем буфер ob_end_clean(); $data = array( 'cart' => $html_cart, 'cart_count' => WC()->cart->get_cart_contents_count(), ); echo wp_send_json($data); } add_action('wp_ajax_get_cartprice', 'woocommerce_get_cartprice'); add_action('wp_ajax_nopriv_get_cartprice', 'woocommerce_get_cartprice'); function woocommerce_get_cartprice() { global $woocommerce; $cart_item_key = $_POST['product']; $quantity = $_POST['quantity']; WC()->cart->set_quantity($cart_item_key, $quantity); $total = $woocommerce->cart->get_subtotal(); $html_cart = ''; if($total == 0){ ob_start(); get_cart_template(); // записываем всё, что в буфере, в переменную $html_cart = ob_get_contents(); // очищаем буфер ob_end_clean(); } wp_send_json( array( 'total' => $total, 'cart' => $html_cart, 'cart_count' => WC()->cart->get_cart_contents_count(), )); } function get_cart_template(){ global $woocommerce; WC()->cart->calculate_totals(); $items = $woocommerce->cart->get_cart(); ?> 0): ?> is_main_query() && !$query->is_feed() && !is_admin() && $query->is_post_type_archive( 'product' ) ) { $meta_query = array( array( ) ); $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'DESC', 'tax_query' => array( 'relation' => 'AND', ) ); $has_variable_ids = array(); $simple_ids = array(); $args[ 'tax_query' ]['relation'] = 'AND'; if (isset($_GET['for_whom'])){ $args[ 'tax_query' ][] = array( 'taxonomy' => 'pa_dlya-kogo', 'field' => 'slug', 'terms' => array($_GET['for_whom']), ); } if (isset($_GET['product_type'])){ $args[ 'tax_query' ][] = array( 'taxonomy' => 'pa_pr_type', 'field' => 'slug', 'terms' => array($_GET['product_type']), ); } $pubished_post = new WP_Query($args); if (!empty($pubished_post->posts)) { foreach ($pubished_post->posts as $pr) { $_product = wc_get_product($pr->ID); if ($_product->is_type('variable')) { // Product has variations $has_variable_ids[] = $pr->ID; } else{ $simple_ids[] = $pr->ID; } } } // var_dump($has_variable_ids); // var_dump($simple_ids); $query->set( 'post_parent__in', $has_variable_ids ); $query->set( 'post_type', array('product', 'product_variation') ); // $query->set('meta_query', $meta_query); } } add_action( 'pre_get_posts', 'be_product_query' ); // Отправка кода и проверка Email add_action( 'wp_ajax_email_validate', 'email_validate' ); add_action( 'wp_ajax_nopriv_email_validate', 'email_validate' ); function email_validate(){ if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { header("Content-Type: application/json"); echo json_encode(array( 'status' => 'error', 'text' => esc_html__( 'Invalid email format', 'woodmart' ) )); } wp_die(); } add_action( 'wp_ajax_send_code', 'send_code' ); add_action( 'wp_ajax_nopriv_send_code', 'send_code' ); function send_code(){ $email = $_POST['email']; $string = rand(1234,9999); $ciphering = "AES-128-CTR"; $options = 0; $iv = '1234567891011121'; $encryption = openssl_encrypt($string, $ciphering, SECRET, $options, $iv); setcookie('login_code', $encryption, time()+60*5, '/'); if(pll_current_language() === 'ru'){ $subject = "Проверочный код Cosmopet -".$string; $message = "Привет, это Cosmopet.\n Держите проверочный код!\n ".$string; } else { $subject = "Cosmopet Verification Code -".$string; $message = "Hello, this is CosmoPet.\n Here's your verification code!\n ".$string; } remove_all_filters( 'wp_mail_from' ); remove_all_filters( 'wp_mail_from_name' ); $headers = array( 'From: Cosmopet ', 'content-type: text/html; charset=utf-8', ); wp_mail( $email, $subject, $message, $headers ); wp_die(); } // Проверка кода add_action( 'wp_ajax_check_code', 'check_code' ); add_action( 'wp_ajax_nopriv_check_code', 'check_code' ); function check_code(){ header("Content-Type: application/json"); $code = $_POST['code']; $email = $_POST['email']; // Генерация пароля $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#!()'; $pass = array(); $alphaLength = strlen($alphabet) - 1; for ($i = 0; $i < 12; $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } $pass = implode($pass); if(isset($_COOKIE['login_code'])) { $string = $_COOKIE['login_code']; $ciphering = "AES-128-CTR"; $options = 0; $iv = '1234567891011121'; $decryption = openssl_decrypt($string, $ciphering, SECRET, $options, $iv); if($decryption === $code){ if(email_exists($email)){ //Авторизуемся $user_id = get_user_by( 'login', $email )->ID; if(empty($user_id)) { $user_id = get_user_by( 'email', $email )->ID; } wp_set_password( $pass, $user_id ); wp_signon( array( 'user_login' => $email, 'user_password' => $pass, 'remember' => 'on', ) ); echo json_encode(array( 'status' => 'success_auth' )); update_field('activated', true, 'user_' . $user_id); exit(); } else { // Регистрируемся $user_id = wp_create_user( $email , $pass , $email ); wp_update_user( [ 'ID' => $user_id, 'user_email' => $email ] ); wp_set_auth_cookie( $user_id, true ); echo json_encode(array( 'status' => 'success_reg' )); update_field('activated', true, 'user_' . $user_id); exit(); } } else { echo json_encode(array( 'status' => 'error', 'text' => esc_html__( 'Invalid code', 'woodmart' ) )); exit(); } } else { echo 'nocoockie'; echo json_encode(array( 'status' => 'error', 'text' => esc_html__( 'The code has expired', 'woodmart' ) )); exit(); } wp_die(); } add_action( 'wp_logout', 'logout_redirect'); function logout_redirect(){ wp_redirect( '/' ); exit(); } require_once( get_template_directory() . '/gp-include/php/multi-currency.php'); require_once( get_template_directory() . '/gp-include/php/pets.php'); require_once( get_template_directory() . '/gp-include/php/user.php'); require_once( get_template_directory() . '/gp-include/php/gp-checkout.php'); require_once( get_template_directory() . '/gp-include/php/gp-filter.php'); require_once( get_template_directory() . '/gp-include/php/tg/login.php'); add_action('init', 'custom_register_activation_endpoint'); function custom_register_activation_endpoint() { add_rewrite_rule('^activate/([^/]*)/?', 'index.php?activation_key=$matches[1]', 'top'); add_rewrite_tag('%activation_key%', '([^&]+)'); } add_action('template_redirect', 'custom_handle_activation_request'); function get_user_by_acf_field_value($field_value) { // Prepare the arguments for WP_User_Query $args = array( 'meta_query' => array( array( 'key' => 'uuid', // Change to your ACF field key 'value' => $field_value, 'compare' => '=', // You can use other comparison operators if needed ), ), ); // Execute the query $user_query = new WP_User_Query($args); // Check for results if (!empty($user_query->get_results())) { return $user_query->get_results(); // Returns an array of WP_User objects } else { return null; // No users found } } function custom_handle_activation_request() { if (get_query_var('activation_key')) { $activation_key = sanitize_text_field(get_query_var('activation_key')); $users = get_user_by_acf_field_value($activation_key); if ($users) { foreach ($users as $user) { $user->set_bio(); // delete_user_meta($user->ID, 'uuid'); // Clean up the activation key update_field('uuid', '', 'user_' . $user->ID); update_field('activated', true, 'user_' . $user->ID); wp_set_auth_cookie($user->ID); wp_redirect('/my-account/'); // Redirect to the homepage or a custom page var_dump($user); exit; } } } } // Отправка кода и проверка Email add_action( 'wp_ajax_email_activate', 'send_activation_email' ); add_action( 'wp_ajax_nopriv_email_activate', 'send_activation_email' ); function send_activation_email() { $user = wp_get_current_user(); $activation_key = sha1($user->user_email . time()); // Generate a unique activation key update_field('uuid', $activation_key, 'user_' . get_current_user_id()); // Save the key in user meta $activation_link = home_url("/activate/$activation_key"); if(pll_current_language() === 'ru'){ $subject = "Активация аккаунта COSMOPET -".$string; $message = " Остался последний шаг!\n Пройдите по ссылке для активации аккаунта:\n ".$activation_link; } else { $subject = "Account activation COSMOPET -".$string; $message = "Last step!\n Follow the link to activate your account\n ".$activation_link; } wp_mail($user->user_email, $subject, $message); } // Отключить уведомления по электронной почте при регистрации пользователя add_filter('new_user_notification_email', '__return_false'); add_action('user_register', 'custom_new_customer_email', 10, 2); function custom_new_customer_email($customer_id) { $user = get_userdata($customer_id); $site_name = get_bloginfo('name'); $to = $user->user_email; if(pll_current_language() === 'ru'){ // Ваш текст письма $subject = 'Добро пожаловать в COSMOPET'; $message = "Приветствуем вас на борту Cosmopet!\n Рады держать вас в курсе наших новостей и акций.\n P.S. Обещаем писать только по делу."; } else{ $subject = 'Welcome to COSMOPET'; $message = "Welcome aboard CosmoPet! \n We are happy to keep you updated on our news, events and promos.\n P.S. We promise to write only to the point"; } // Убедитесь, что письма отправляются в правильном формате $headers = array('Content-Type: text/plain; charset=UTF-8'); // Отправка письма wp_mail($to, $subject, $message, $headers); } // if ( !function_exists('wp_new_user_notification') ) { // function wp_new_user_notification( $user_id, $plaintext_pass = '' ) { // $user = new WP_User($user_id); // $to = stripslashes($user->user_email); // if(pll_current_language() === 'ru'){ // // Ваш текст письма // $subject = 'Добро пожаловать в COSMOPET'; // $message = "Приветствуем вас на борту Cosmopet!\n // Рады держать вас в курсе наших новостей и акций.\n // P.S. Обещаем писать только по делу."; // } // else{ // $subject = 'Welcome to COSMOPET'; // $message = "Welcome aboard CosmoPet! \n // We are happy to keep you updated on our news, events and promos.\n // P.S. We promise to write only to the point"; // } // // Убедитесь, что письма отправляются в правильном формате // $headers = array('Content-Type: text/plain; charset=UTF-8'); // // Отправка письма // wp_mail($to, $subject, $message, $headers); // } // } add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_catalog_ordering_args'); function custom_woocommerce_catalog_ordering_args($args) { $args['orderby'] = 'date'; // Сортируем по дате $args['order'] = 'DESC'; // Последние добавленные первыми return $args; } add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2); function change_existing_currency_symbol( $currency_symbol, $currency ) { $currency_symbol = 'AED'; return $currency_symbol; } // ADD TO CART DUNCTION CUSTOM add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); function woocommerce_ajax_add_to_cart() { $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id'])); $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']); $variation_id = absint($_POST['variation_id']); $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity); $product_status = get_post_status($product_id); if($variation_id){ $obj = new WC_Product_Variation($variation_id); $stock = $obj->get_stock_quantity(); if ($quantity > $stock){ $quantity = $stock; } } else{ $obj = wc_get_product( $product_id ); $stock = $obj->get_stock_quantity(); if ($quantity > $stock){ $quantity = $stock; } } if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) { do_action('woocommerce_ajax_added_to_cart', $product_id); if ('yes' === get_option('woocommerce_cart_redirect_after_add')) { wc_add_to_cart_message(array($product_id => $quantity), true); } ob_start(); get_cart_template(); // записываем всё, что в буфере, в переменную $html_cart = ob_get_contents(); // очищаем буфер ob_end_clean(); } $data = array( 'cart' => $html_cart, 'cart_count' => WC()->cart->get_cart_contents_count(), ); echo wp_send_json($data); } // Удаляет графу доставка из страницы успешного заказа add_filter('woocommerce_order_details_after_order_table', 'custom_hide_shipping_info', 10, 1); function custom_hide_shipping_info($order) { // Удаляем строку с информацией о доставке remove_action('woocommerce_order_details_after_order_table', 'woocommerce_order_shipping_info', 10); } // add_filter('woocommerce_add_error', function($error) { // if($error === 'An account is already registered with your email address. Please log in.') { // return 'An account is already registered with your email address. '; // } // return $error; // }); add_filter('woocommerce_registration_error_email_exists', 'custom_email_exists_error_message', 10, 2); function custom_email_exists_error_message($default_message, $email) { // Ваше кастомное сообщение об ошибке $custom_message = __('An account is already registered with your email address. ', 'woocommerce'); return $custom_message; } add_filter('woocommerce_apply_coupon', 'limit_to_one_coupon', 10, 3); add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 ); function one_applied_coupon_only( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; // For more than 1 applied coupons only if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){ // Remove the first applied coupon keeping only the last appield coupon $cart->remove_coupon( reset($coupons) ); } } add_action('wp_footer', 'add_facebook_pixel_events'); function add_facebook_pixel_events() { // 1. Событие AddToCart (Добавление в корзину) // Предполагаем, что кнопка имеет класс 'add_to_cart_button' (стандарт WooCommerce) if (is_product() || is_shop() || is_cart()) { // Только на страницах товаров, магазина или корзины ?> 'Site options', // Заголовок страницы в админке 'menu_title' => 'Site options', // Название в меню админки 'menu_slug' => 'site-general-settings', // Уникальный slug для страницы 'capability' => 'edit_posts', // Права доступа (кто может редактировать) 'redirect' => false, // Отключить редирект на дочерние страницы 'post_id' => 'options', // Указывает, что данные сохраняются глобально 'autoload' => false, // Не загружать данные автоматически при старте WP )); }