__('Основное меню', 'your-theme-domain'), 'socials' => __('Соцсети', 'your-theme-domain'), 'footer-bottom' => __('Нижнее меню в подвале', 'your-theme-domain'), )); add_theme_support('custom-logo', array( 'height' => 100, 'width' => 400, 'flex-height' => true, 'flex-width' => true, )); add_theme_support('post-thumbnails'); } add_action('after_setup_theme', 'theme_setup'); function theme_enqueue_styles_scripts() { $style_ver = filemtime(get_template_directory() . '/frontend/dist/assets/main.css'); $script_ver = filemtime(get_template_directory() . '/frontend/dist/assets/main2.js'); wp_enqueue_style('main-style', get_template_directory_uri() . '/frontend/dist/assets/main.css', array(), $style_ver); wp_enqueue_script('main-script2', get_template_directory_uri() . '/frontend/dist/assets/main2.js', array(), $script_ver, true); // Preconnect for Google Fonts //wp_enqueue_style('google-fonts-preconnect', 'https://fonts.gstatic.com', [], null, 'all'); //wp_resource_hints(['https://fonts.googleapis.com', 'https://fonts.gstatic.com'], 'preconnect'); // Enqueue Google Fonts wp_enqueue_style('google-fonts-raleway', 'https://fonts.googleapis.com/css2?family=Raleway:wght@400;500;600&display=swap', false); wp_enqueue_style('google-fonts-roboto', 'https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=swap', false); } add_action('wp_enqueue_scripts', 'theme_enqueue_styles_scripts'); add_filter('nav_menu_css_class', 'change_menu_item_css_class', 10, 4); function change_menu_item_css_class($classes, $item, $args, $depth) { // Удаляем нежелательные классы $classes = array_diff($classes, array('page_item', 'page-item-' . $item->ID)); $classes = array_diff($classes, array('page_item', 'page-item-' . $item->ID)); // Добавляем класс 'menu-item' $classes[] = 'menu-item'; return $classes; } function get_asset(string $path) { return get_template_directory_uri() . '/frontend/dist/' . $path; } function mytheme_widget_areas() { // Регистрация левого сайдбара register_sidebar(array( 'name' => 'Левый сайдбар', 'id' => 'left-sidebar', 'description' => 'Виджеты в этой области будут показаны в левой части сайта.', 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '

', 'after_title' => '

', )); // Регистрация правого сайдбара register_sidebar(array( 'name' => 'Правый сайдбар', 'id' => 'right-sidebar', 'description' => 'Виджеты в этой области будут показаны в правой части сайта.', 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '

', 'after_title' => '

', )); } add_action('widgets_init', 'mytheme_widget_areas'); class Upcoming_Events_Widget extends WP_Widget { function __construct() { parent::__construct( 'upcoming_events_widget', // ID виджета 'Upcoming Events', // Название виджета array('description' => 'Displays upcoming events') // Описание ); } public function widget($args, $instance) { include get_template_directory() . '/widgets/upcoming-events-widget-template.php'; } // Форма в админ-панели для настройки виджета public function form($instance) { $title = !empty($instance['title']) ? $instance['title'] : 'Новое название'; ?>

', '', $output); $output = str_replace('', '', $output); // Заменяем разделитель на нужный нам класс. $output = str_replace('»', '', $output); // Заменяем теги ссылок. $output = str_replace(']*>/', '', $output); return $output; } function custom_pagination($query = null) { global $wp_query; $query = $query ?: $wp_query; $current_page = max(1, get_query_var('paged')); $total_pages = $query->max_num_pages; $show_items = 3; // Количество страниц для вывода в начале и в конце $range = 1; // Диапазон страниц вокруг текущей страницы if (1 == $total_pages) { return; // Если страница всего одна, пагинация не нужна } if ( defined('LANG') && LANG == 'en' ){ $txt['back'] = 'Back'; $txt['next'] = 'Next'; } else { $txt['back'] = 'Назад'; $txt['next'] = 'Далее'; } echo ''; } function my_theme_scripts() { if (is_front_page() || (is_category() && !is_paged())) { wp_enqueue_script('my-load-more', get_template_directory_uri() . '/js/load-main-scroll.js', array('jquery'), null, true); $query_vars = array('post_type' => 'post', 'posts_per_page' => 10); if (is_category()) { $category = get_queried_object(); $query_vars['cat'] = $category->term_id; } $query = new WP_Query($query_vars); wp_localize_script('my-load-more', 'my_load_more_params', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'posts' => json_encode($query->query_vars), 'current_page' => max(1, get_query_var('paged')), // Начальная страница 'max_page' => $query->max_num_pages )); } } add_action('wp_enqueue_scripts', 'my_theme_scripts'); function loadmore_ajax_handler() { $args = json_decode(stripslashes($_POST['query']), true); $args['paged'] = $_POST['page'] + 1; $args['post_status'] = 'publish'; $args['posts_per_page'] = 12; // Проверка на категорию, если она есть в параметрах запроса if (isset($args['cat']) && !empty($args['cat'])) { $args['cat'] = $args['cat']; } else { $args['cat'] = [-17, -20, -21]; } query_posts($args); if (have_posts()) : while (have_posts()) : the_post(); get_template_part('content', 'post'); endwhile; endif; die; } add_action('wp_ajax_loadmore', 'loadmore_ajax_handler'); add_action('wp_ajax_nopriv_loadmore', 'loadmore_ajax_handler'); /* * Фильтр добавлен для модификации стандартной формы плагина Contact Form ( Срезаем span элементы, в которые оборачивается input ). * Работает в связке с отключенными требованиями плагина - define( 'WPCF7_AUTOP', false ); * В файле wp-config.php * */ add_filter('wpcf7_form_elements', function ($content) { $content = preg_replace('/<(span).*?class="\s*(?:.*\s)?wpcf7-form-control-wrap(?:\s[^"]+)?\s*"[^\>]*>(.*)<\/\1>/i', '\2', $content); return $content; }); function show_post_image($post = null, $size = 'large') { if (has_post_thumbnail($post)) { return get_the_post_thumbnail($post, $size); } else { return ''; } } add_action('rest_api_init', function () { register_rest_route('agroexpert/v1', '/posts-by-date/', array( 'methods' => 'GET', 'callback' => 'get_posts_by_date', 'permission_callback' => '__return_true', // Доступно для чтения всеми )); }); function get_posts_by_date($request) { global $wpdb; // Глобальный объект базы данных WordPress // SQL-запрос для получения уникальных дат публикации постов $query = " SELECT DISTINCT DATE(post_date) as date FROM {$wpdb->posts} WHERE post_status IN ('publish', 'future') AND post_type = 'post' ORDER BY date DESC "; // Выполнение запроса $result = $wpdb->get_results($query); // Преобразование результатов в массив дат $dates = array_map(function ($item) { return $item->date; }, $result); return new WP_REST_Response($dates, 200); } function setup_future_hook() { // Replace native future_post function with replacement remove_action('future_event', '_future_post_hook'); add_action('future_event', 'publish_future_post_now'); } function publish_future_post_now($id) { // Set new post's post_status to "publish" rather than "future." wp_publish_post($id); } add_action('init', 'setup_future_hook'); add_action('restrict_manage_posts', 'add_author_filter_to_posts_admin'); function add_author_filter_to_posts_admin() { global $post_type; // Убедитесь, что этот фильтр применяется только к типу поста 'post' if ('post' !== $post_type) { return; } // Получаем пользователей с ролью 'author' $authors = get_users(array('role' => '', 'orderby' => 'display_name', 'order' => 'ASC')); // Проверяем, установлен ли фильтр $selected = isset($_GET['custom_author']) ? $_GET['custom_author'] : ''; // Начинаем выводить HTML выпадающего списка echo ''; } add_action('pre_get_posts', 'filter_posts_by_custom_author'); function filter_posts_by_custom_author($query) { global $pagenow; // Применяем фильтр только в админ-панели и только для основного запроса на странице списка постов if (is_admin() && 'edit.php' === $pagenow && $query->is_main_query()) { // Проверяем, установлен ли наш фильтр if (!empty($_GET['custom_author'])) { $custom_author_id = $_GET['custom_author']; // Фильтруем посты по автору $query->set('author', $custom_author_id); } } } function custom_search_rewrite_rule() { add_rewrite_rule( '^search/$', 'index.php?s=' . get_query_var('s'), 'top' ); add_rewrite_rule('^search/?$', 'index.php?s=', 'top'); add_rewrite_rule('^search/page/([0-9]+)/?$', 'index.php?s=&paged=$matches[1]', 'top'); } add_action('init', 'custom_search_rewrite_rule'); add_filter('relevanssi_hits_filter', 'rlv_gather_categories', 99); function rlv_gather_categories($hits) { global $rlv_categories_present; $rlv_categories_present = array(); foreach ($hits[0] as $hit) { $terms = get_the_terms($hit->ID, 'category'); if (is_array($terms)) { foreach ($terms as $term) { $rlv_categories_present[$term->term_id] = $term->name; } } } asort($rlv_categories_present); return $hits; } function plural_form_extended($number, $forms, $additionalWord = '') { $cases = array(2, 0, 1, 1, 1, 2); $index = ($number % 100 > 4 && $number % 100 < 20) ? 2 : $cases[min($number % 10, 5)]; // Склонение дополнительного слова, если оно передано $additionalForm = ''; if ($additionalWord) { $additionalIndex = $index > 0 ? 1 : 0; // Простая логика для "найдено" $additionalForm = $additionalWord[$additionalIndex] . ' '; } return $additionalForm . $number . ' ' . $forms[$index]; } add_filter('wpseo_breadcrumb_links', 'custom_search_breadcrumbs'); function custom_search_breadcrumbs($links) { if (is_search()) { // Получаем поисковый запрос $search_query = get_search_query(); // Перебираем все ссылки, чтобы найти и изменить нужный элемент foreach ($links as &$link) { if (strpos($link['text'], 'Результаты поиска') !== false) { if ($search_query === "") { $link['text'] = 'Поиск'; } else { $link['text'] = 'Результаты поиска для запроса "' . esc_html($search_query) . '"'; } $link['url'] = home_url('/search/') . urlencode($search_query) . '/'; break; // Прерываем цикл после изменения нужного элемента } } unset($link); } return $links; } function include_future_posts_in_date_archive($query) { // Убедимся, что мы находимся в основном запросе и на странице архива по дате if ($query->is_main_query() && $query->is_date()) { // Изменяем запрос так, чтобы он включал посты с датой публикации в будущем $query->set('post_status', array('publish', 'future')); } } add_action('pre_get_posts', 'include_future_posts_in_date_archive'); function template_500_error($template) { // Проверяем, является ли текущая страница страницей ошибки 500 if (is_500()) { return get_stylesheet_directory() . '/500.php'; // Путь к вашему собственному шаблону 500 ошибки } return $template; } add_filter('template_include', 'template_500_error'); function is_500() { // Проверяем, является ли текущий код состояния HTTP 500 return get_query_var('error', false) === 500; } function change_image_size_dimensions() { update_option('large_size_w', 1080); update_option('large_size_h', 0); update_option('medium_size_w', 400); update_option('medium_size_h', 0); } add_action('init', 'change_image_size_dimensions'); add_filter('big_image_size_threshold', '__return_false'); function auto_add_category_by_slug_to_new_post($post_ID, $post, $update) { $category_slug = 'all-events'; // Slug рубрики для добавления $category = get_term_by('slug', $category_slug, 'category'); // Если рубрика с таким slug существует if ($category && !has_category($category->term_id, $post_ID)) { wp_set_post_categories($post_ID, array($category->term_id), true); } } //add_action('save_post', 'auto_add_category_by_slug_to_new_post', 10, 3); function get_category_name($post = null) { $categories = get_the_category($post); $categories = array_filter($categories, function (WP_Term $category) { return $category->slug !== 'all-events'; }); $categories = array_values($categories); $category_name = !empty($categories) ? esc_html($categories[0]->name) : 'Все события'; return $category_name; } function get_category_name_en($post = null) { $categories = get_the_category($post); $categories = array_filter($categories, function (WP_Term $category) { return $category->slug !== 'en'; }); $categories = array_values($categories); $category_name = !empty($categories) ? esc_html($categories[0]->name) : 'Все события'; return $category_name; } // Добавляем функцию для формирования мета-тегов страницы function custom_meta_tags() { $sitename = get_bloginfo('name'); $meta_tags = ''; $og_tags = ''; $og_tags .= ''; $og_tags .= ''. PHP_EOL; // Получаем заголовок страницы if (is_single() || is_page()) { $current_url = get_permalink(); $post = get_post(); // Получаем объект текущего поста или страницы $title = get_the_title($post).' - '.$sitename; // Получаем заголовок текущего поста или страницы $excerpt = get_the_excerpt($post); if (has_excerpt()) { $description = $excerpt; } elseif (strlen($excerpt) > 300) { $description = wp_trim_words($excerpt, 30, '...'); } else { $description = $excerpt; } $tags = get_the_tags($post); // Получаем теги текущего поста или страницы $keywords = ''; // Переменная для хранения ключевых слов if ($tags) { $keywords = implode(', ', wp_list_pluck($tags, 'name')); // Формируем строку с тегами через запятую } $post_thumbnail_id = get_post_thumbnail_id($post->ID); $post_thumbnail_url = wp_get_attachment_image_src($post_thumbnail_id, 'full'); if ($post_thumbnail_url) { $og_image = esc_url($post_thumbnail_url[0]); $og_tags .= ''. PHP_EOL; $og_tags .= ''. PHP_EOL; } $og_tags .= ''. PHP_EOL; } elseif (is_category()) { $category = get_queried_object(); // Получаем объект текущей рубрики $current_url = get_term_link($category); $title = $category->name.': Новости, комментарии по теме - '.$sitename; // Получаем название текущей рубрики $description = $category->description; // Получаем описание текущей рубрики $keywords = $category->name; // Ключевые слова - название рубрики } elseif (is_home()) { $current_url = get_site_url(); $title = $sitename; // Получаем название сайта для главной страницы $description = get_bloginfo('description'); // Получаем описание сайта для главной страницы $keywords = ''; // Для главной страницы ключевые слова оставляем пустыми $og_tags .= ''. PHP_EOL; } // Добавляем мета-теги только в случае, если их значения не пусты if (!empty($current_url)) { $og_tags .= '' . PHP_EOL; } if (!empty($title)) { $meta_tags .= '' . esc_html($title) . ''. PHP_EOL; $og_tags .= ''. PHP_EOL; } if (!empty($description)) { $description = wp_strip_all_tags($description); $meta_tags .= ''. PHP_EOL; $og_tags .= ''. PHP_EOL; } if (!empty($keywords)) { $meta_tags .= ''. PHP_EOL; } // Выводим мета-теги echo $meta_tags; echo $og_tags; } add_action('wpcf7_before_send_mail', 'my_custom_contact_form_handler', 10, 3); function my_custom_contact_form_handler($contact_form, $abort, $submission) { // Получаем ID формы $form_id = $contact_form->id(); if ( $form_id == '0ddb83c' ) { // Получаем данные формы $submission = WPCF7_Submission::get_instance(); if ($submission) { $posted_data = $submission->get_posted_data(); // Подключаемся к базе данных WordPress global $wpdb; // Определяем таблицу в базе данных WordPress в зависимости от ID формы $table_name = $wpdb->prefix . 'subusers'; $wpdb->insert( $table_name, array( 'mail' => $posted_data['your-email'], 'status' => 0, 'date' => current_time('mysql') ), array( '%s', // Формат для строкового поля '%d', // Формат для цифрового поля '%s' // Формат для поля с датой и временем ) ); } } } function last_sticky_post() { //$pinned_post = get_field('pinned_post', 'options'); static $last = null; // array to pinned post if ( $last !== null){ return $last; } $sticky_posts = array_reverse(get_option('sticky_posts')); $published_sticky_posts = array(); foreach ($sticky_posts as $post_id) { $post = get_post($post_id); if ($post->post_status == 'publish') { //$published_sticky_posts[] = $post_id; $last = $post; break; // Выходим из цикла, так как нашли последний опубликованный закрепленный пост } } return $last; } function get_latest_sticky_post_by_category($category_id) { // Получение всех закрепленных постов $sticky_posts = get_option('sticky_posts'); if (empty($sticky_posts)) { return null; } // Получение всех постов, которые включены в закрепленные посты $args = array( 'post__in' => $sticky_posts, 'posts_per_page' => -1, // Получаем все закрепленные посты 'ignore_sticky_posts' => 1, // Игнорируем параметры отображения закрепленных постов ); $posts = get_posts($args); // Получаем ID всех подрубрик рубрики $category_ids = get_term_children($category_id, 'category'); $category_ids[] = $category_id; // Включаем основную рубрику // Фильтрация постов по категории и её подрубрикам $filtered_posts = array_filter($posts, function($post) use ($category_ids) { $post_categories = wp_get_post_categories($post->ID); return array_intersect($post_categories, $category_ids); }); if (empty($filtered_posts)) { return null; } // Сортировка постов по дате в обратном порядке usort($filtered_posts, function($a, $b) { return strtotime($b->post_date) - strtotime($a->post_date); }); // Возвращаем самый последний пост return $filtered_posts[0]; } // отправка писем через свой почтовый сервис function agroxpert_send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'mail.vetandlife.ru'; $phpmailer->SMTPAuth = true; $phpmailer->Port = 465; $phpmailer->Username = 'news@mail.agroexpert.press'; $phpmailer->Password = 'O6K!]aZDNJ'; $phpmailer->SMTPSecure = 'ssl'; $phpmailer->From = 'news@mail.agroexpert.press'; $phpmailer->FromName = 'Агроэксперт'; } add_action( 'phpmailer_init', 'agroxpert_send_smtp_email' ); function my_custom_mail_sent( $contact_form ){ $log_file = WP_CONTENT_DIR . '/contact.log'; $form_id = $contact_form->id(); //if ( $form_id == '19' ) { $submission = WPCF7_Submission::get_instance(); $posted_data = $submission->get_posted_data(); $mail = $posted_data['your-email']; global $wpdb; $table_name = $wpdb->prefix . 'subusers'; $hash = md5('775+'.$mail); $query = $wpdb->prepare("SELECT * FROM $table_name WHERE mail = %s", $mail); $result = $wpdb->get_row($query); if ( !$result ) { //аdd to table $result = $wpdb->insert( $table_name, array( 'mail' => $mail, 'status' => 0, 'date' => current_time('mysql'), 'hash' => $hash, ), array( '%s', '%d', '%s', '%s' ) ); } // } $hash_link = home_url().'/subscript?id='.$hash; $subject = 'Подписка на рассылку АгроЭксперт'; $message = " Здравствуйте!\n Для подтверждения подписки на рассылку издания «АгроЭксперт» перейдите по ссылке ниже:\n $hash_link.\n\n Если вы не отправляли заявку просто проигнорируйте это письмо."; $headers = array('Content-Type: text/plain; charset=UTF-8'); // Отправка письма wp_mail($mail, $subject, $message, $headers); return; } add_action('wpcf7_mail_sent', 'my_custom_mail_sent' ); /** * */ if (!function_exists('view')){ function view ($view, $data = array(), $layer = null){ ob_start(); if (is_array($data)) extract($data); if ($layer !== null){ $content = view($view, $data); require $layer; } else require $view; return trim(ob_get_clean()); } } //все рубрики англ версии function get_expression_en( $str = false ) { #cache result static $res = null; if ($res !== null) { return $res; } $parent_cat_id = 740; // Получаем все подрубрики данной рубрики $subcategories = get_terms(array( 'taxonomy' => 'category', 'child_of' => $parent_cat_id, 'hide_empty' => false, 'fields' => 'ids' )); // Добавляем ID родительской рубрики в начало массива подрубрик array_unshift($subcategories, $parent_cat_id); $res = $subcategories; return $res; } // возвращаем все исключенные рубрики function get_expression_parts() { #cache result static $res = null; if ($res !== null) { return $res; } $subcategories_en = get_expression_en(); $additional_excludes = [ '17', '20', '21', $parent_cat_id ]; $all_excludes = array_merge( $additional_excludes, $subcategories_en ); $res = implode(',', $all_excludes); // Преобразуем массив ID в строку, разделенную запятыми return $res; } function get_priority_category_en($post_id = null) { if ($post_id === null) { $post_id = get_the_ID(); } // Получаем массив категорий поста $categories = get_the_category($post_id); if (empty($categories)) { return null; } $en_category = null; // Проходим по всем категориям поста foreach ($categories as $category) { // Проверяем, содержит ли название категории 'en' if (stripos($category->name, 'en') !== false) { $en_category = $category->name; } else { // Если нашли категорию, не содержащую 'en', возвращаем её название return $category->name; } } // Если нет категорий, кроме 'en', возвращаем категорию 'en' return $en_category; } // рубрики английской версии function use_custom_template_for_en_subcategories($template) { if (is_category()) { $category = get_queried_object(); if ($category->term_id == 762) { //parthers $new_template = locate_template('en/category-partners-en.php'); if ($new_template) { return $new_template; } } // Проверяем, является ли текущая категория подрубрикой "EN" $parent_id = $category->parent; if ($parent_id && $parent_id == get_cat_ID('EN')) { define('LANG', 'en'); // Устанавливаем путь к вашему новому шаблону $new_template = locate_template('en/category-en-sub.php'); if ($new_template) { return $new_template; } } } else if (is_single()) { $categories = get_the_category(); foreach ($categories as $category) { // Проверяем, является ли текущая категория или ее родительская категория "EN" if ($category->term_id == get_cat_ID('EN') || $category->parent == get_cat_ID('EN')) { // Устанавливаем путь к вашему новому шаблону $new_template = locate_template('single-en.php'); if ($new_template) { return $new_template; } } } } return $template; } add_filter('template_include', 'use_custom_template_for_en_subcategories'); /** * update rubrics */ function add_posts_to_category_744() { // Получаем ID рубрики 740 и всех ее подрубрик $parent_category_id = 740; $subcategories = get_categories(array( 'child_of' => $parent_category_id, 'hide_empty' => false )); // Массив ID всех подрубрик 740 $subcategory_ids = wp_list_pluck($subcategories, 'term_id'); $all_category_ids = array_merge(array($parent_category_id), $subcategory_ids); // Запрос для получения постов, которые имеют рубрику 740 или любую из ее подрубрик $args = array( 'post_type' => 'post', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => $all_category_ids, 'operator' => 'IN' ), ), ); // Получаем все посты с указанной рубрикой или ее подрубриками $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); // Получаем ID текущего поста $post_id = get_the_ID(); // Получаем все рубрики текущего поста $post_categories = wp_get_post_categories($post_id); // Проверяем, есть ли у поста только рубрика 740 if (count($post_categories) == 1 && in_array($parent_category_id, $post_categories)) { // Добавляем пост в рубрику с ID 744 wp_set_post_categories($post_id, array_merge($post_categories, array(744))); } else { // Проверяем, если у поста есть подрубрика 740, но нет основной рубрики 740 $has_subcategory = array_intersect($post_categories, $subcategory_ids); if ($has_subcategory && !in_array($parent_category_id, $post_categories)) { // Добавляем основную рубрику 740 wp_set_post_categories($post_id, array_merge($post_categories, array($parent_category_id))); } } } // Сбрасываем пост данные wp_reset_postdata(); } } /** function add_custom_admin_menu() { add_menu_page( 'Update Posts Categories', // Заголовок страницы 'Update Categories EN', // Текст меню 'manage_options', // Возможность доступа (только администраторы) 'update-categories', // Уникальный идентификатор страницы 'update_categories_callback' // Функция для отображения контента страницы ); } add_action('admin_menu', 'add_custom_admin_menu');*/ function add_custom_admin_menu() { add_submenu_page( 'tools.php', // Родительское меню (в данном случае "Инструменты") 'Update Posts Categories', // Заголовок страницы 'Update Categories EN', // Текст меню 'manage_options', // Возможность доступа (только администраторы) 'update-categories', // Уникальный идентификатор страницы 'update_categories_callback' // Функция для отображения контента страницы ); } add_action('admin_menu', 'add_custom_admin_menu'); function update_categories_callback() { if (isset($_POST['update_categories'])) { add_posts_to_category_744(); echo '

Posts have been updated successfully.

'; } ?>

Update Posts Categories