diff --git a/wp-content/themes/cosmopet/functions.php b/wp-content/themes/cosmopet/functions.php index 3c179fa..ed584db 100644 --- a/wp-content/themes/cosmopet/functions.php +++ b/wp-content/themes/cosmopet/functions.php @@ -5,16 +5,6 @@ require_once __DIR__ . '/vendor/autoload.php'; // для работы Composer Timber\Timber::init(); - - -/* Подключение файлов с разной бизнес-логикой */ -// function require_all_temp_functions() { -// foreach (glob(__DIR__ . '/temp-functions/*.php') as $file) { -// require_once $file; -// } -// } -// require_all_temp_functions(); - // require once вместо include использовать! require_once __DIR__ . '/temp-functions/cart-logic.php'; require_once __DIR__ . '/temp-functions/timber-logic.php'; @@ -22,25 +12,8 @@ require_once __DIR__ . '/temp-functions/woocommerce-logic.php'; require_once __DIR__ . '/temp-functions/modules-logic.php'; require_once __DIR__ . '/temp-functions/ajax-logic.php'; require_once __DIR__ . '/temp-functions/shortcodes-logic.php'; - - - - - -add_action('init', function() { - if (function_exists('wpseo_load_textdomain')) { - wpseo_load_textdomain(); - } - if (function_exists('pll_load_textdomain')) { - pll_load_textdomain(); - } -}, 1); - - - - - - +require_once __DIR__ . '/temp-functions/blog-logic.php'; +require_once __DIR__ . '/temp-functions/filters-logic.php'; // include_module('forms'); // include_module('shop'); @@ -52,840 +25,4 @@ add_action('init', function() { -//Ajax подгрузка товаров в архиве -add_action( 'wp_ajax_nopriv_get_products', 'get_products' ); -add_action( 'wp_ajax_get_products', 'get_products' ); - -function get_products() { - global $post; - - if (function_exists('WC')) { - WC(); - } - - // Потом Timber - - $context = Timber::context(); - $context['get_page'] = empty($_POST['get_page']) ? 1 : $_POST['get_page']; - $context['criteria_for_new_product'] = date('Y-m-d', strtotime('-30 days')); - $context['get_category'] = isset($_POST['get_category']) ? $_POST['get_category'] : NULL; - $context['get_category_type'] = isset($_POST['get_category_type']) ? $_POST['get_category_type'] : NULL; - - // Задаем количество постов для подзагрузки Ajax - $posts_per_page = 12; - - $args = array( - 'post_type' => 'product', - 'post_status' => 'publish', - 'posts_per_page' => $posts_per_page, - 'paged' => $context['get_page'], - 'has_password' => FALSE - ); - - $count_args = array( - 'post_type' => 'product', - 'post_status' => 'publish', - 'posts_per_page' => -1, - 'has_password' => FALSE - ); - - if ($context['get_category'] != NULL) { - $categories = [ - 'tax_query' => array( - array( - 'taxonomy' => $context['get_category_type'], - 'field' => 'term_id', - 'terms' => array($context['get_category']), - 'operator' => 'IN' - ), - array( - 'taxonomy' => 'product_visibility', - 'field' => 'slug', - 'terms' => 'exclude-from-catalog', - 'operator' => 'NOT IN' - ) - ) - ]; - $args = array_merge($args, $categories); - $count_args = array_merge($count_args, $categories); - } - - $products = new WP_Query($args); - $products = new Timber\PostQuery($products, 'Timber\Integrations\WooCommerce\Product'); - - $context['posts'] = $products; - - $context['count'] = count(Timber::get_posts($count_args)); - - if ($context['count'] <= $context['get_page'] * $posts_per_page) { - $context['ended'] = true; - } - - Timber::render( 'woocommerce/archive-product/archive-product-ajaxload.twig', $context ); - - die(); -} - -function get_product_info ($id, $type) { - if (!$id) { - return ''; - } - $product = wc_get_product($id); - if (!$product) { - return ''; - } - if ($type == 'price') { - return $product->get_price(); - } elseif ($type == 'weight') { - return $product->get_weight() ? $product->get_weight() . ' кг' : ''; - } - return ''; -} - -function get_add_to_cart_button ($id) { - $product = wc_get_product( $id ); - return ''. pll__('Добавить в корзину') .''; -} - -function get_collection_siblings ($term) { - if (!$term) { - return []; - } - - $args = array( - 'posts_per_page' => -1, - 'post_type' => 'product', - 'order' => 'ASC', - 'order_by' => 'name', - 'tax_query' => [ - [ - 'taxonomy' => 'pa_collection', - 'terms' => $term, - 'field' => 'id', - ] - ], - ); - - $siblings = get_posts($args); - - $sibl_arr = []; - - foreach( $siblings as $sibling ) { - $sibl_arr [] = $sibling; - } - - return $sibl_arr; -} - -register_sidebar( array( - 'name' => 'Сайдбар для фильтров товаров', - 'id' => 'sidebar_filters', - 'before_widget' => '
', - 'after_widget' => '
', - 'before_title' => '

', - 'after_title' => '

', -) ); - - -/** - * Email Validation - * Validates the format of the provided email via AJAX. - */ -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(); -} - -/** - * Send Verification Code - * Generates a random code, encrypts it, stores it in a cookie, and sends it via email. - */ -add_action('wp_ajax_send_code', 'send_code'); -add_action('wp_ajax_nopriv_send_code', 'send_code'); - -function send_code() { - $email = sanitize_email($_POST['email']); - if (!is_email($email)) { - wp_die(json_encode(['status' => 'error', 'text' => 'Invalid email'])); - } - - // Generate a random 4-digit code - $code = sprintf("%04d", mt_rand(1000, 9999)); - - // Store code in a secure session for 5 minutes - session_start(); - $_SESSION['login_code'] = [ - 'code' => $code, - 'email' => $email, - 'expires' => time() + (5 * 60) - ]; - session_write_close(); - - // Prepare email content - $language = function_exists('pll_current_language') ? pll_current_language() : 'en'; - if ($language === 'ru') { - $subject = "Проверочный код Cosmopet - $code"; - $message = "Привет, это Cosmopet.\nВаш проверочный код: $code\nДействителен 5 минут."; - } else { - $subject = "Cosmopet Verification Code - $code"; - $message = "Hello, this is CosmoPet.\nYour verification code: $code\nValid for 5 minutes."; - } - - // Configure email headers - $headers = array( - 'From: Cosmopet ', - 'content-type: text/plain; charset=utf-8', - 'Reply-To: pro@cosmopet.shop', - ); - - // Send email with fallback logging - $sent = wp_mail($email, $subject, $message, $headers); - if ($sent) { - wp_die(json_encode(['status' => 'success', 'message' => 'Code sent'])); - } else { - error_log("Email failed to send to $email. Error: " . json_encode(error_get_last())); - wp_die(json_encode(['status' => 'error', 'text' => 'Failed to send code'])); - } -} - -/** - * Check Verification Code - * Validates the user-entered code, logs in or registers the user. - */ -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 = sanitize_text_field($_POST['code']); - $email = sanitize_email($_POST['email']); - - session_start(); - if (isset($_SESSION['login_code']) && is_array($_SESSION['login_code'])) { - $stored_data = $_SESSION['login_code']; - if ($stored_data['email'] === $email && $stored_data['code'] === $code && $stored_data['expires'] > time()) { - // Generate a random password - $password = wp_generate_password(12, true, false); - - if (email_exists($email)) { - // Log in existing user - $user = get_user_by('email', $email); - wp_set_password($password, $user->ID); - $login = wp_signon([ - 'user_login' => $email, - 'user_password' => $password, - 'remember' => true - ]); - - if (!is_wp_error($login)) { - // Redirect to admin dashboard - update_user_meta($user->ID, 'activated', true); - wp_die(json_encode(['status' => 'success_auth', 'redirect' => admin_url()])); - } - } else { - // Register new user - $user_id = wp_create_user($email, $password, $email); - if (!is_wp_error($user_id)) { - wp_update_user([ - 'ID' => $user_id, - 'display_name' => $email - ]); - $login = wp_signon([ - 'user_login' => $email, - 'user_password' => $password, - 'remember' => true - ]); - - if (!is_wp_error($login)) { - update_user_meta($user_id, 'activated', true); - wp_die(json_encode(['status' => 'success_reg', 'redirect' => admin_url()])); - } - } - } - } - } - - // Cleanup expired session data - if (isset($_SESSION['login_code']) && $stored_data['expires'] <= time()) { - unset($_SESSION['login_code']); - } - session_write_close(); - - wp_die(json_encode(['status' => 'error', 'text' => 'Invalid or expired code'])); -} - -/** - * Logout Redirect - * Redirects to the homepage after user logout. - */ -add_action('wp_logout', 'logout_redirect'); - -function logout_redirect() { - wp_redirect('/'); - exit(); -} - -add_filter( 'woocommerce_price_trim_zeros', '__return_true' ); - -function add_comment_like() { - global $wpdb; - $table_name = $wpdb->prefix . 'cosmopet_likes'; - $wpdb->show_errors(); - if (!is_user_logged_in()) { - wp_send_json_error('Необходимо авторизоваться'); - die(); - } - $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0; - $user_id = get_current_user_id(); - if ($comment_id) { - $comment_exists = get_comment($comment_id); - if (!$comment_exists) { - echo '0'; - die(); - } - $existing_like = $wpdb->get_var($wpdb->prepare( - "SELECT COUNT(*) FROM $table_name WHERE comment_id = %d AND user_id = %d", - $comment_id, $user_id - )); - if (!$existing_like) { - $result = $wpdb->insert( - $table_name, - array( - 'user_id' => $user_id, - 'comment_id' => $comment_id, - 'date_added' => current_time('mysql') - ), - array('%d', '%d', '%s') - ); - } else { - $result = $wpdb->delete( - $table_name, - array( - 'user_id' => $user_id, - 'comment_id' => $comment_id - ), - array('%d', '%d') - ); - } - $likes = get_comment_likes_count($comment_id); - wp_send_json(array( - 'count' => $likes, - 'is_liked' => !$existing_like - )); - } else { - wp_send_json(array('count' => 0, 'is_liked' => false)); - } - die(); -} -add_action('wp_ajax_add_comment_like', 'add_comment_like'); - -function add_post_like() { - global $wpdb; - $table_name = $wpdb->prefix . 'cosmopet_likes'; - if (!is_user_logged_in()) { - wp_send_json_error('Необходимо авторизоваться'); - die(); - } - $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; - $user_id = get_current_user_id(); - if ($post_id) { - $existing_like = $wpdb->get_var($wpdb->prepare( - "SELECT COUNT(*) FROM $table_name WHERE post_id = %d AND user_id = %d", - $post_id, $user_id - )); - if (!$existing_like) { - $wpdb->insert( - $table_name, - array( - 'user_id' => $user_id, - 'post_id' => $post_id, - 'date_added' => current_time('mysql') - ), - array('%d', '%d', '%s') - ); - } else { - $wpdb->delete( - $table_name, - array( - 'user_id' => $user_id, - 'post_id' => $post_id - ), - array('%d', '%d') - ); - } - $likes = get_post_likes_count($post_id); - wp_send_json(array( - 'count' => $likes, - 'is_liked' => !$existing_like - )); - } - die(); -} -add_action('wp_ajax_add_post_like', 'add_post_like'); - -function check_user_likes() { - global $wpdb; - $table_name = $wpdb->prefix . 'cosmopet_likes'; - if (!is_user_logged_in()) { - wp_send_json_error('Необходимо авторизоваться'); - die(); - } - $user_id = get_current_user_id(); - $liked_posts = $wpdb->get_col($wpdb->prepare( - "SELECT post_id FROM $table_name WHERE user_id = %d AND post_id > 0", - $user_id - )); - $liked_comments = $wpdb->get_col($wpdb->prepare( - "SELECT comment_id FROM $table_name WHERE user_id = %d AND comment_id > 0", - $user_id - )); - $response = array( - 'posts' => $liked_posts, - 'comments' => $liked_comments - ); - echo json_encode($response); - die(); -} -add_action('wp_ajax_check_user_likes', 'check_user_likes'); - - - -function get_post_likes_count($post_id) { - global $wpdb; - $table_name = $wpdb->prefix . 'cosmopet_likes'; - $count = $wpdb->get_var($wpdb->prepare( - "SELECT COUNT(*) FROM $table_name WHERE post_id = %d", - $post_id - )); - return $count ? $count : 0; -} - -function get_comment_likes_count($comment_id) { - global $wpdb; - $table_name = $wpdb->prefix . 'cosmopet_likes'; - $count = $wpdb->get_var($wpdb->prepare( - "SELECT COUNT(*) FROM $table_name WHERE comment_id = %d", - $comment_id - )); - return $count ? $count : 0; -} - -function is_user_liked_post($post_id) { -if (!is_user_logged_in()) { - return false; -} -global $wpdb; -$table_name = $wpdb->prefix . 'cosmopet_likes'; -$user_id = get_current_user_id(); -$result = $wpdb->get_var($wpdb->prepare( - "SELECT COUNT(*) FROM $table_name WHERE post_id = %d AND user_id = %d", - $post_id, $user_id -)); -return $result > 0; -} - - -function is_user_liked_comment($comment_id) { -if (!is_user_logged_in()) { - return false; -} -global $wpdb; -$table_name = $wpdb->prefix . 'cosmopet_likes'; -$user_id = get_current_user_id(); -$result = $wpdb->get_var($wpdb->prepare( - "SELECT COUNT(*) FROM $table_name WHERE comment_id = %d AND user_id = %d", - $comment_id, $user_id -)); -return $result > 0; -} - - -add_filter('comment_form_logged_in', '__return_empty_string'); - - - // Создание таблицы -function create_likes_table() { - global $wpdb; - $table_name = $wpdb->prefix . 'cosmopet_likes'; - $charset_collate = $wpdb->get_charset_collate(); - $sql = "CREATE TABLE IF NOT EXISTS $table_name ( - id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) NOT NULL, - post_id bigint(20) DEFAULT '0', - comment_id bigint(20) DEFAULT '0', - date_added datetime DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (id), - KEY post_id (post_id), - KEY comment_id (comment_id), - KEY user_id (user_id), - UNIQUE KEY user_post (user_id, post_id, comment_id) - ) $charset_collate;"; - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); - dbDelta($sql); -} -add_action('after_switch_theme', 'create_likes_table'); - - - -add_filter('woocommerce_product_data_tabs', function($tabs) { - $tabs['composition_tab'] = array( - 'label' => 'Состав', - 'target' => 'composition_product_data', - 'class' => array('composition_tab'), - 'priority' => 60, - ); - $tabs['feeding_tab'] = array( - 'label' => 'Рекомендации по кормлению', - 'target' => 'feeding_product_data', - 'class' => array('feeding_tab'), - 'priority' => 61, - ); - $tabs['important_tab'] = array( - 'label' => 'Важно', - 'target' => 'important_product_data', - 'class' => array('important_tab'), - 'priority' => 62, - ); - return $tabs; -}); - - -add_action('woocommerce_product_data_panels', function() { - global $post; - $composition = get_post_meta($post->ID, '_composition', true); - echo '
'; - woocommerce_wp_textarea_input([ - 'id' => '_composition', - 'label' => 'Состав', - 'desc_tip' => true, - 'description' => 'Введите состав товара', - 'value' => $composition - ]); - echo '
'; -}); - - -add_action('woocommerce_product_data_panels', function() { - global $post; - $feeding = get_post_meta($post->ID, '_feeding_recommendations', true); - echo '
'; - woocommerce_wp_textarea_input([ - 'id' => '_feeding_recommendations', - 'label' => 'Рекомендации по кормлению', - 'desc_tip' => true, - 'description' => 'Введите рекомендации по кормлению', - 'value' => $feeding - ]); - echo '
'; -}); - - -add_action('woocommerce_product_data_panels', function() { - global $post; - $important = get_post_meta($post->ID, '_important', true); - echo '
'; - woocommerce_wp_textarea_input([ - 'id' => '_important', - 'label' => 'Важно', - 'desc_tip' => true, - 'description' => 'Введите важную информацию', - 'value' => $important - ]); - echo '
'; -}); - -add_action('woocommerce_process_product_meta', function($post_id) { - if (isset($_POST['_composition'])) { - update_post_meta($post_id, '_composition', sanitize_textarea_field($_POST['_composition'])); - } - if (isset($_POST['_feeding_recommendations'])) { - update_post_meta($post_id, '_feeding_recommendations', sanitize_textarea_field($_POST['_feeding_recommendations'])); - } - if (isset($_POST['_important'])) { - update_post_meta($post_id, '_important', sanitize_textarea_field($_POST['_important'])); - } -}); -// Добавление поля для выбора рекомендуемых товаров -function register_recommended_products_acf_field() { - if (function_exists('acf_add_local_field_group')) { - acf_add_local_field_group(array( - 'key' => 'group_recommended_products', - 'title' => 'Рекомендуемые товары', - 'fields' => array( - array( - 'key' => 'field_recommended_products', - 'label' => 'Выберите рекомендуемые товары', - 'name' => 'recommended_products', - 'type' => 'relationship', - 'instructions' => 'Выберите товары, которые будут отображаться в секции "вашему питомцу может понравиться"', - 'required' => 0, - 'conditional_logic' => 0, - 'post_type' => array( - 0 => 'product', - ), - 'filters' => array( - 0 => 'search', - 1 => 'taxonomy', - ), - 'return_format' => 'object', - 'min' => '', - 'max' => 8, - ), - ), - 'location' => array( - array( - array( - 'param' => 'post_type', - 'operator' => '==', - 'value' => 'product', - ), - ), - ), - 'menu_order' => 0, - 'position' => 'normal', - 'style' => 'default', - 'label_placement' => 'top', - 'instruction_placement' => 'label', - 'hide_on_screen' => '', - )); - } -} -add_action('acf/init', 'register_recommended_products_acf_field'); - -add_action('wp_footer', 'remove_view_cart_button_js'); -function remove_view_cart_button_js() { - ?> - - cart; - $count = $cart->get_cart_contents_count(); - $total = $cart->get_total('raw'); // Числовая сумма - $total_html = wc_cart_totals_order_total_html(); // Форматированная сумма - - wp_send_json_success([ - 'contents' => $contents, - 'footer' => $footer, - 'count' => $count, - 'total' => $total_html, - 'total_raw' => $total - ]); -} - -add_action('template_redirect', 'custom_redirect_cart_page'); -function custom_redirect_cart_page() { - if (is_cart()) { - wp_redirect(home_url('/')); - exit; - } -} - -add_action('wp_enqueue_scripts', 'remove_woocommerce_styles_on_checkout', 9999); -function remove_woocommerce_styles_on_checkout() { - // Проверяем, что мы на странице чекаута - if (function_exists('is_checkout') && is_checkout() && !is_order_received_page()) { - wp_deregister_style('woocommerce-layout'); - wp_deregister_style('woocommerce-smallscreen'); - wp_deregister_style('woocommerce-general'); - - // Дополнительно: отключить другие стили WooCommerce - wp_dequeue_style('select2'); - wp_deregister_style('select2'); - } -} - - -// Добавляем hreflang теги для cosmopet.shop -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 '' . "\n"; - echo '' . "\n"; - } -} - -add_action('wp_head', 'custom_checkout_padding'); -function custom_checkout_padding() { - // Проверяем, что это страница Checkout - if (is_checkout() && !is_admin()) { - ?> - - 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_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'); - - - -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; - } - } - - } -} diff --git a/wp-content/themes/cosmopet/global-functions/multilang-functions.php b/wp-content/themes/cosmopet/global-functions/multilang-functions.php index 474529e..b10321d 100644 --- a/wp-content/themes/cosmopet/global-functions/multilang-functions.php +++ b/wp-content/themes/cosmopet/global-functions/multilang-functions.php @@ -1,4 +1,15 @@ 'Неверный ID товара')); - wp_die(); + // Выводим hreflang-теги + echo '' . "\n"; + echo '' . "\n"; } +} - $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity); - - if ($passed_validation) { - $added = WC()->cart->add_to_cart($product_id, $quantity); - if ($added) { - error_log('Product added to cart: ' . $product_id); // Отладка - // Подготавливаем фрагменты корзины - ob_start(); - woocommerce_mini_cart(); - $mini_cart = ob_get_clean(); - - // Фрагменты для стандартной корзины и кастомного счетчика - $fragments = array( - 'div.widget_shopping_cart_content' => '
' . $mini_cart . '
', - '.mini-profile__button--counter' => '
' . WC()->cart->get_cart_contents_count() . '
' - ); - - wp_send_json_success(array( - 'message' => 'Товар успешно добавлен в корзину', - 'fragments' => apply_filters('woocommerce_add_to_cart_fragments', $fragments), - 'cart_hash' => apply_filters('woocommerce_add_to_cart_hash', WC()->cart->get_cart_hash(), array()) - )); - } else { - error_log('Failed to add product to cart: ' . $product_id); // Отладка - wp_send_json_error(array('message' => 'Не удалось добавить товар в корзину')); - } - } else { - error_log('Validation failed for product: ' . $product_id); // Отладка - wp_send_json_error(array('message' => 'Ошибка валидации товара')); - } - wp_die(); -}} \ No newline at end of file diff --git a/wp-content/themes/cosmopet/temp-functions/blog-logic.php b/wp-content/themes/cosmopet/temp-functions/blog-logic.php new file mode 100644 index 0000000..c146d1b --- /dev/null +++ b/wp-content/themes/cosmopet/temp-functions/blog-logic.php @@ -0,0 +1,197 @@ +prefix . 'cosmopet_likes'; + $wpdb->show_errors(); + if (!is_user_logged_in()) { + wp_send_json_error('Необходимо авторизоваться'); + die(); + } + $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0; + $user_id = get_current_user_id(); + if ($comment_id) { + $comment_exists = get_comment($comment_id); + if (!$comment_exists) { + echo '0'; + die(); + } + $existing_like = $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM $table_name WHERE comment_id = %d AND user_id = %d", + $comment_id, $user_id + )); + if (!$existing_like) { + $result = $wpdb->insert( + $table_name, + array( + 'user_id' => $user_id, + 'comment_id' => $comment_id, + 'date_added' => current_time('mysql') + ), + array('%d', '%d', '%s') + ); + } else { + $result = $wpdb->delete( + $table_name, + array( + 'user_id' => $user_id, + 'comment_id' => $comment_id + ), + array('%d', '%d') + ); + } + $likes = get_comment_likes_count($comment_id); + wp_send_json(array( + 'count' => $likes, + 'is_liked' => !$existing_like + )); + } else { + wp_send_json(array('count' => 0, 'is_liked' => false)); + } + die(); +} +add_action('wp_ajax_add_comment_like', 'add_comment_like'); + +function add_post_like() { + global $wpdb; + $table_name = $wpdb->prefix . 'cosmopet_likes'; + if (!is_user_logged_in()) { + wp_send_json_error('Необходимо авторизоваться'); + die(); + } + $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; + $user_id = get_current_user_id(); + if ($post_id) { + $existing_like = $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM $table_name WHERE post_id = %d AND user_id = %d", + $post_id, $user_id + )); + if (!$existing_like) { + $wpdb->insert( + $table_name, + array( + 'user_id' => $user_id, + 'post_id' => $post_id, + 'date_added' => current_time('mysql') + ), + array('%d', '%d', '%s') + ); + } else { + $wpdb->delete( + $table_name, + array( + 'user_id' => $user_id, + 'post_id' => $post_id + ), + array('%d', '%d') + ); + } + $likes = get_post_likes_count($post_id); + wp_send_json(array( + 'count' => $likes, + 'is_liked' => !$existing_like + )); + } + die(); +} +add_action('wp_ajax_add_post_like', 'add_post_like'); + +function check_user_likes() { + global $wpdb; + $table_name = $wpdb->prefix . 'cosmopet_likes'; + if (!is_user_logged_in()) { + wp_send_json_error('Необходимо авторизоваться'); + die(); + } + $user_id = get_current_user_id(); + $liked_posts = $wpdb->get_col($wpdb->prepare( + "SELECT post_id FROM $table_name WHERE user_id = %d AND post_id > 0", + $user_id + )); + $liked_comments = $wpdb->get_col($wpdb->prepare( + "SELECT comment_id FROM $table_name WHERE user_id = %d AND comment_id > 0", + $user_id + )); + $response = array( + 'posts' => $liked_posts, + 'comments' => $liked_comments + ); + echo json_encode($response); + die(); +} +add_action('wp_ajax_check_user_likes', 'check_user_likes'); + + +function get_post_likes_count($post_id) { + global $wpdb; + $table_name = $wpdb->prefix . 'cosmopet_likes'; + $count = $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM $table_name WHERE post_id = %d", + $post_id + )); + return $count ? $count : 0; +} + +function get_comment_likes_count($comment_id) { + global $wpdb; + $table_name = $wpdb->prefix . 'cosmopet_likes'; + $count = $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM $table_name WHERE comment_id = %d", + $comment_id + )); + return $count ? $count : 0; +} + +function is_user_liked_post($post_id) { +if (!is_user_logged_in()) { + return false; +} +global $wpdb; +$table_name = $wpdb->prefix . 'cosmopet_likes'; +$user_id = get_current_user_id(); +$result = $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM $table_name WHERE post_id = %d AND user_id = %d", + $post_id, $user_id +)); +return $result > 0; +} + + +function is_user_liked_comment($comment_id) { +if (!is_user_logged_in()) { + return false; +} +global $wpdb; +$table_name = $wpdb->prefix . 'cosmopet_likes'; +$user_id = get_current_user_id(); +$result = $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM $table_name WHERE comment_id = %d AND user_id = %d", + $comment_id, $user_id +)); +return $result > 0; +} + + +add_filter('comment_form_logged_in', '__return_empty_string'); + + + // Создание таблицы +function create_likes_table() { + global $wpdb; + $table_name = $wpdb->prefix . 'cosmopet_likes'; + $charset_collate = $wpdb->get_charset_collate(); + $sql = "CREATE TABLE IF NOT EXISTS $table_name ( + id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) NOT NULL, + post_id bigint(20) DEFAULT '0', + comment_id bigint(20) DEFAULT '0', + date_added datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY post_id (post_id), + KEY comment_id (comment_id), + KEY user_id (user_id), + UNIQUE KEY user_post (user_id, post_id, comment_id) + ) $charset_collate;"; + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); + dbDelta($sql); +} +add_action('after_switch_theme', 'create_likes_table'); \ No newline at end of file diff --git a/wp-content/themes/cosmopet/temp-functions/cart-logic.php b/wp-content/themes/cosmopet/temp-functions/cart-logic.php index ab4fa67..1b867f3 100644 --- a/wp-content/themes/cosmopet/temp-functions/cart-logic.php +++ b/wp-content/themes/cosmopet/temp-functions/cart-logic.php @@ -1,2 +1,70 @@ cart; + $count = $cart->get_cart_contents_count(); + $total = $cart->get_total('raw'); // Числовая сумма + $total_html = wc_cart_totals_order_total_html(); // Форматированная сумма + + wp_send_json_success([ + 'contents' => $contents, + 'footer' => $footer, + 'count' => $count, + 'total' => $total_html, + 'total_raw' => $total + ]); +} + +add_action('template_redirect', 'custom_redirect_cart_page'); +function custom_redirect_cart_page() { + if (is_cart()) { + wp_redirect(home_url('/')); + exit; + } +} + +add_action('wp_enqueue_scripts', 'remove_woocommerce_styles_on_checkout', 9999); +function remove_woocommerce_styles_on_checkout() { + // Проверяем, что мы на странице чекаута + if (function_exists('is_checkout') && is_checkout() && !is_order_received_page()) { + wp_deregister_style('woocommerce-layout'); + wp_deregister_style('woocommerce-smallscreen'); + wp_deregister_style('woocommerce-general'); + + // Дополнительно: отключить другие стили WooCommerce + wp_dequeue_style('select2'); + wp_deregister_style('select2'); + } +} + +add_action('wp_head', 'custom_checkout_padding'); +function custom_checkout_padding() { + // Проверяем, что это страница Checkout + if (is_checkout() && !is_admin()) { + ?> + + 'Сайдбар для фильтров товаров', + 'id' => 'sidebar_filters', + 'before_widget' => '
', + 'after_widget' => '
', + 'before_title' => '

', + 'after_title' => '

', +) ); + +// Для кнопки "Применить фильтр" +add_filter('wbw_filter_submit_button_text', 'change_wbw_filter_button_text'); +function change_wbw_filter_button_text($text) { + return 'Ваш текст'; // Например, "Фильтровать" или "Поиск" +} + +// Для кнопки сброса (если есть) +add_filter('wbw_filter_reset_button_text', 'change_wbw_reset_button_text'); +function change_wbw_reset_button_text($text) { + return 'Сбросить'; +} \ No newline at end of file diff --git a/wp-content/themes/cosmopet/temp-functions/login-logic.php b/wp-content/themes/cosmopet/temp-functions/login-logic.php new file mode 100644 index 0000000..71b1798 --- /dev/null +++ b/wp-content/themes/cosmopet/temp-functions/login-logic.php @@ -0,0 +1,238 @@ + 'error', + 'text' => esc_html__('Invalid email format', 'woodmart') + )); + } + wp_die(); +} + +/** + * Send Verification Code + * Generates a random code, encrypts it, stores it in a cookie, and sends it via email. + */ +add_action('wp_ajax_send_code', 'send_code'); +add_action('wp_ajax_nopriv_send_code', 'send_code'); + +function send_code() { + $email = sanitize_email($_POST['email']); + if (!is_email($email)) { + wp_die(json_encode(['status' => 'error', 'text' => 'Invalid email'])); + } + + // Generate a random 4-digit code + $code = sprintf("%04d", mt_rand(1000, 9999)); + + // Store code in a secure session for 5 minutes + session_start(); + $_SESSION['login_code'] = [ + 'code' => $code, + 'email' => $email, + 'expires' => time() + (5 * 60) + ]; + session_write_close(); + + // Prepare email content + $language = function_exists('pll_current_language') ? pll_current_language() : 'en'; + if ($language === 'ru') { + $subject = "Проверочный код Cosmopet - $code"; + $message = "Привет, это Cosmopet.\nВаш проверочный код: $code\nДействителен 5 минут."; + } else { + $subject = "Cosmopet Verification Code - $code"; + $message = "Hello, this is CosmoPet.\nYour verification code: $code\nValid for 5 minutes."; + } + + // Configure email headers + $headers = array( + 'From: Cosmopet ', + 'content-type: text/plain; charset=utf-8', + 'Reply-To: pro@cosmopet.shop', + ); + + // Send email with fallback logging + $sent = wp_mail($email, $subject, $message, $headers); + if ($sent) { + wp_die(json_encode(['status' => 'success', 'message' => 'Code sent'])); + } else { + error_log("Email failed to send to $email. Error: " . json_encode(error_get_last())); + wp_die(json_encode(['status' => 'error', 'text' => 'Failed to send code'])); + } +} + +/** + * Check Verification Code + * Validates the user-entered code, logs in or registers the user. + */ +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 = sanitize_text_field($_POST['code']); + $email = sanitize_email($_POST['email']); + + session_start(); + if (isset($_SESSION['login_code']) && is_array($_SESSION['login_code'])) { + $stored_data = $_SESSION['login_code']; + if ($stored_data['email'] === $email && $stored_data['code'] === $code && $stored_data['expires'] > time()) { + // Generate a random password + $password = wp_generate_password(12, true, false); + + if (email_exists($email)) { + // Log in existing user + $user = get_user_by('email', $email); + wp_set_password($password, $user->ID); + $login = wp_signon([ + 'user_login' => $email, + 'user_password' => $password, + 'remember' => true + ]); + + if (!is_wp_error($login)) { + // Redirect to admin dashboard + update_user_meta($user->ID, 'activated', true); + wp_die(json_encode(['status' => 'success_auth', 'redirect' => admin_url()])); + } + } else { + // Register new user + $user_id = wp_create_user($email, $password, $email); + if (!is_wp_error($user_id)) { + wp_update_user([ + 'ID' => $user_id, + 'display_name' => $email + ]); + $login = wp_signon([ + 'user_login' => $email, + 'user_password' => $password, + 'remember' => true + ]); + + if (!is_wp_error($login)) { + update_user_meta($user_id, 'activated', true); + wp_die(json_encode(['status' => 'success_reg', 'redirect' => admin_url()])); + } + } + } + } + } + + // Cleanup expired session data + if (isset($_SESSION['login_code']) && $stored_data['expires'] <= time()) { + unset($_SESSION['login_code']); + } + session_write_close(); + + wp_die(json_encode(['status' => 'error', 'text' => 'Invalid or expired code'])); +} + +/** + * Logout Redirect + * Redirects to the homepage after user logout. + */ +add_action('wp_logout', 'logout_redirect'); + +function logout_redirect() { + wp_redirect('/'); + 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() { + error_log(123); + $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_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'); + +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; + } + } + + } +} + diff --git a/wp-content/themes/cosmopet/temp-functions/woocommerce-logic.php b/wp-content/themes/cosmopet/temp-functions/woocommerce-logic.php index 01fee10..d605aed 100644 --- a/wp-content/themes/cosmopet/temp-functions/woocommerce-logic.php +++ b/wp-content/themes/cosmopet/temp-functions/woocommerce-logic.php @@ -12,4 +12,278 @@ add_action('after_setup_theme', function() { add_theme_support('comments'); update_option('default_comment_status', 'open'); -}); \ No newline at end of file +}); + + + +//Ajax подгрузка товаров в архиве +add_action( 'wp_ajax_nopriv_get_products', 'get_products' ); +add_action( 'wp_ajax_get_products', 'get_products' ); + +function get_products() { + global $post; + + if (function_exists('WC')) { + WC(); + } + + // Потом Timber + + $context = Timber::context(); + $context['get_page'] = empty($_POST['get_page']) ? 1 : $_POST['get_page']; + $context['criteria_for_new_product'] = date('Y-m-d', strtotime('-30 days')); + $context['get_category'] = isset($_POST['get_category']) ? $_POST['get_category'] : NULL; + $context['get_category_type'] = isset($_POST['get_category_type']) ? $_POST['get_category_type'] : NULL; + + // Задаем количество постов для подзагрузки Ajax + $posts_per_page = 12; + + $args = array( + 'post_type' => 'product', + 'post_status' => 'publish', + 'posts_per_page' => $posts_per_page, + 'paged' => $context['get_page'], + 'has_password' => FALSE + ); + + $count_args = array( + 'post_type' => 'product', + 'post_status' => 'publish', + 'posts_per_page' => -1, + 'has_password' => FALSE + ); + + if ($context['get_category'] != NULL) { + $categories = [ + 'tax_query' => array( + array( + 'taxonomy' => $context['get_category_type'], + 'field' => 'term_id', + 'terms' => array($context['get_category']), + 'operator' => 'IN' + ), + array( + 'taxonomy' => 'product_visibility', + 'field' => 'slug', + 'terms' => 'exclude-from-catalog', + 'operator' => 'NOT IN' + ) + ) + ]; + $args = array_merge($args, $categories); + $count_args = array_merge($count_args, $categories); + } + + $products = new WP_Query($args); + $products = new Timber\PostQuery($products, 'Timber\Integrations\WooCommerce\Product'); + + $context['posts'] = $products; + + $context['count'] = count(Timber::get_posts($count_args)); + + if ($context['count'] <= $context['get_page'] * $posts_per_page) { + $context['ended'] = true; + } + + Timber::render( 'woocommerce/archive-product/archive-product-ajaxload.twig', $context ); + + die(); +} + + +//Получить аттрибуты товара по ID +function get_product_info ($id, $type) { + if (!$id) { + return ''; + } + $product = wc_get_product($id); + if (!$product) { + return ''; + } + if ($type == 'price') { + return $product->get_price(); + } elseif ($type == 'weight') { + return $product->get_weight() ? $product->get_weight() . ' кг' : ''; + } + return ''; +} + +//Кнопка добавления в корзину +function get_add_to_cart_button ($id) { + $product = wc_get_product( $id ); + return ''. pll__('Добавить в корзину') .''; +} + +//Получить товары из одной подборки по весу +function get_collection_siblings ($term) { + if (!$term) { + return []; + } + + $args = array( + 'posts_per_page' => -1, + 'post_type' => 'product', + 'order' => 'ASC', + 'order_by' => 'name', + 'tax_query' => [ + [ + 'taxonomy' => 'pa_collection', + 'terms' => $term, + 'field' => 'id', + ] + ], + ); + + $siblings = get_posts($args); + + $sibl_arr = []; + + foreach( $siblings as $sibling ) { + $sibl_arr [] = $sibling; + } + + return $sibl_arr; +} + +add_filter( 'woocommerce_price_trim_zeros', '__return_true' ); + +add_filter('woocommerce_product_data_tabs', function($tabs) { + $tabs['composition_tab'] = array( + 'label' => 'Состав', + 'target' => 'composition_product_data', + 'class' => array('composition_tab'), + 'priority' => 60, + ); + $tabs['feeding_tab'] = array( + 'label' => 'Рекомендации по кормлению', + 'target' => 'feeding_product_data', + 'class' => array('feeding_tab'), + 'priority' => 61, + ); + $tabs['important_tab'] = array( + 'label' => 'Важно', + 'target' => 'important_product_data', + 'class' => array('important_tab'), + 'priority' => 62, + ); + return $tabs; +}); + + +add_action('woocommerce_product_data_panels', function() { + global $post; + $composition = get_post_meta($post->ID, '_composition', true); + echo '
'; + woocommerce_wp_textarea_input([ + 'id' => '_composition', + 'label' => 'Состав', + 'desc_tip' => true, + 'description' => 'Введите состав товара', + 'value' => $composition + ]); + echo '
'; +}); + + +add_action('woocommerce_product_data_panels', function() { + global $post; + $feeding = get_post_meta($post->ID, '_feeding_recommendations', true); + echo '
'; + woocommerce_wp_textarea_input([ + 'id' => '_feeding_recommendations', + 'label' => 'Рекомендации по кормлению', + 'desc_tip' => true, + 'description' => 'Введите рекомендации по кормлению', + 'value' => $feeding + ]); + echo '
'; +}); + + +add_action('woocommerce_product_data_panels', function() { + global $post; + $important = get_post_meta($post->ID, '_important', true); + echo '
'; + woocommerce_wp_textarea_input([ + 'id' => '_important', + 'label' => 'Важно', + 'desc_tip' => true, + 'description' => 'Введите важную информацию', + 'value' => $important + ]); + echo '
'; +}); + +add_action('woocommerce_process_product_meta', function($post_id) { + if (isset($_POST['_composition'])) { + update_post_meta($post_id, '_composition', sanitize_textarea_field($_POST['_composition'])); + } + if (isset($_POST['_feeding_recommendations'])) { + update_post_meta($post_id, '_feeding_recommendations', sanitize_textarea_field($_POST['_feeding_recommendations'])); + } + if (isset($_POST['_important'])) { + update_post_meta($post_id, '_important', sanitize_textarea_field($_POST['_important'])); + } +}); +// Добавление поля для выбора рекомендуемых товаров +function register_recommended_products_acf_field() { + if (function_exists('acf_add_local_field_group')) { + acf_add_local_field_group(array( + 'key' => 'group_recommended_products', + 'title' => 'Рекомендуемые товары', + 'fields' => array( + array( + 'key' => 'field_recommended_products', + 'label' => 'Выберите рекомендуемые товары', + 'name' => 'recommended_products', + 'type' => 'relationship', + 'instructions' => 'Выберите товары, которые будут отображаться в секции "вашему питомцу может понравиться"', + 'required' => 0, + 'conditional_logic' => 0, + 'post_type' => array( + 0 => 'product', + ), + 'filters' => array( + 0 => 'search', + 1 => 'taxonomy', + ), + 'return_format' => 'object', + 'min' => '', + 'max' => 8, + ), + ), + 'location' => array( + array( + array( + 'param' => 'post_type', + 'operator' => '==', + 'value' => 'product', + ), + ), + ), + 'menu_order' => 0, + 'position' => 'normal', + 'style' => 'default', + 'label_placement' => 'top', + 'instruction_placement' => 'label', + 'hide_on_screen' => '', + )); + } +} +add_action('acf/init', 'register_recommended_products_acf_field'); + +add_action('wp_footer', 'remove_view_cart_button_js'); +function remove_view_cart_button_js() { + ?> + +