Version, "all"); wp_enqueue_style("main-styles"); wp_register_style("desktop-styles", get_template_directory_uri() . "/assets/css/app-desktop.css", [], wp_get_theme()->Version, "(min-width: 992px)"); wp_enqueue_style("desktop-styles"); wp_register_style("mobile-styles", get_template_directory_uri() . "/assets/css/app-mobile.css", [], wp_get_theme()->Version, "(max-width: 992px)"); wp_enqueue_style("mobile-styles"); wp_register_style("roboto-font", "https://fonts.googleapis.com/css2?family=PT+Sans:wght@400;700&family=Roboto:wght@400;700&display=swap"); wp_enqueue_style("roboto-font"); wp_register_style("advtoken-styles", get_template_directory_uri() . "/assets/css/app-advtoken.css", [], wp_get_theme()->Version, "all"); wp_enqueue_style("advtoken-styles"); } /** * Подключение кастомных скриптов (TODO: когда Ильгиз доделает, скачать, пока по ссылке) */ add_action( 'wp_enqueue_scripts', 'register_theme_scripts' ); function register_theme_scripts() : void { wp_register_script("main-scripts", get_template_directory_uri() . "/assets/js/app-min.js", [], wp_get_theme()->Version, true); wp_enqueue_script("main-scripts"); if( wp_is_mobile() ) { if($_SERVER['HTTP_SIDE'] === 'gprofile') { wp_register_script("doubleclick", "https://securepubads.g.doubleclick.net/tag/js/gpt.js"); wp_enqueue_script("doubleclick"); } else { wp_register_script("adfox", "https://yandex.ru/ads/system/context.js"); wp_enqueue_script("adfox"); } } } /** * Отключение лишних стилей */ add_action( 'wp_enqueue_scripts', 'clear_scripts_styles', 999 ); function clear_scripts_styles() : void { foreach ([ "wp-block-library", "elasticpress-related-posts-block", "classic-theme-styles", "global-styles", "ajax-load-more-filters", "ajax-load-more-layouts", "ajax-load-more-paging", "searchterm-highlighting" ] as $item) { wp_dequeue_style($item); wp_deregister_style($item); } } /** * Инициализация свойств темы */ add_action( 'after_setup_theme', 'theme_setup' ); function theme_setup() : void { set_post_thumbnail_size( 782, 440, true ); add_image_size( 'thumb-1200', 1200, 675, true ); add_image_size( 'thumb-782', 782, 440, true ); add_image_size( 'thumb-590', 590, 332, true ); add_image_size( 'thumb-500', 500, 281, true ); add_image_size( 'thumb-400', 400, 225, true ); add_image_size( 'thumb-345', 345, 213, true ); add_image_size( 'thumb-320', 320, 180, true ); add_image_size( 'thumb-290', 290, 179, true ); add_image_size( 'thumb-264', 264, 172, true ); add_image_size( 'thumb-224', 224, 138, true ); /** * https://wordpress.org/plugins/wp-retina-2x/ * https://www.wpbeginner.com/wp-tutorials/how-to-create-additional-image-sizes-in-wordpress/ */ register_nav_menus ( [ 'header_menu' => __( 'Меню в шапке', 'profilemagazine' ), 'burger_menu_1' => __( 'Меню в бургере 1', 'profilemagazine' ), 'burger_menu_2' => __( 'Меню в бургере 2', 'profilemagazine' ), 'other_categories' => __( 'Другие рубрики', 'profilemagazine' ), 'footer_menu' => __( 'Меню в подвале', 'profilemagazine' ), ] ); add_theme_support( 'post-thumbnails', ['post', 'profile_article', 'anew', 'guest-author', 'yellow', 'journal_issue'] ); } /** * Добавление в head стилей для брендированных рубрик */ add_action('wp_head', 'branding_styles'); function branding_styles() : void { if ( is_branding() ) { get_template_part("template-parts/header/branding"); } } /** * Проверка брендирования * @return bool */ function is_branding() : bool { if( is_tag() || is_category() ) { return get_term_meta( get_queried_object_id(), "type", true ) === "branding" || get_term_meta( get_queried_object()->parent, "type", true ) === "branding"; } if ( is_single() ) { return get_term_meta( get_the_category( get_queried_object_id() )[0]->term_id, 'type', true) === "branding" || get_term_meta( get_the_category( get_queried_object_id() )[0]->parent, 'type', true) === "branding"; } return false; } /** * Возвращает значение мета-поля брендированной рубрики * @return string * TODO:Заменить дефолтную мету */ function get_branding_meta(string $meta = 'taxonomy_logo_image') : string { if( is_category() ) { $term_id = get_term_meta( get_queried_object_id(), 'type', true) === "branding" ? get_queried_object_id() : get_queried_object()->parent; } else { $term_id = get_term_meta( get_the_category( get_queried_object_id() )[0]->term_id, 'type', true) === "branding" ? get_the_category( get_queried_object_id() )[0]->term_id : get_the_category( get_queried_object_id() )[0]->parent; } return get_term_meta( $term_id, $meta, true ); } /** * Возвращает идентификатор рубрики для текущей страницы, если это архив рубрики или страница материала, * идентификатор термина другой таксономии в архиве таксономии * @param int $id * @return int */ function get_current_page_main_taxonomy_term_id( int $id = 0 ) : ?int { if( ( is_category() || is_tag() || is_author() ) && !$id ) { return get_queried_object_id(); } else { $id = $id ? $id : get_queried_object_id(); return get_the_category( $id )[0]->term_id; } return 0; } /** * Выводит в теге style критические стили для текущего шаблона */ function current_template_stylesheet() : void { } /** * Возвращает html баннера локальной рекламной системы по идентификатору * @param int $zone_id * @return string */ function get_banner_by_zone_id( int $zone_id = 0, bool $show_on_mobile = false ) : string { if( !$zone_id || ( wp_is_mobile() && !$show_on_mobile ) ) { return ""; } if ( @include_once("/var/www/revive/www/delivery/alocal.php") ) { if ( !isset($phpAds_context) ) { $phpAds_context = []; } $phpAds_raw = view_local("", $zone_id, 0, 0, "", "", "0", $phpAds_context, ""); return $phpAds_raw["html"]; } return ""; } /** * Walker для главного меню, добавляет классов элементам списка */ class Profile_Menu_Walker extends Walker_Nav_Menu { const menu_classes = [ "header_menu" => [ "li_class" => "nav-item", "a_class" => "nav-link nav-link--color" ], "burger_menu_1" => [ "li_class" => "burger-menu burger-menu__color", "a_class" => "" ], "burger_menu_2" => [ "li_class" => "burger-menu burger-menu__bn", "a_class" => "" ], "other_categories" => [ "li_class" => "burger-menu__sub", "a_class" => "" ], "footer_menu" => [ "li_class" => "nav-footer-item", "a_class" => "nav-footer-item__link" ], ]; function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) { $color = get_post_meta($data_object->ID, "_menu_item_color", true); $color = $color ? $color : "black"; //$li_class = self::menu_classes[$args->theme_location]["li_class"] . implode(" ", $data_object->classes); $li_class = self::menu_classes[$args->theme_location]["li_class"] ?? ''; $classes_part = ''; if (is_array($data_object->classes)) { $classes_part = implode(" ", $data_object->classes); } else { $classes_part = $data_object->classes ?? ''; } $li_class .= ' ' . trim($classes_part); $a_class = self::menu_classes[$args->theme_location]["a_class"]; $link_attr = ! empty( $data_object->attr_title ) ? ' title="' . esc_attr( $data_object->attr_title ) .'"' : ''; $link_attr .= ! empty( $data_object->target ) ? ' target="' . esc_attr( $data_object->target ) .'"' : ''; $link_attr .= ! empty( $data_object->xfn ) ? ' rel="' . esc_attr( $data_object->xfn ) .'"' : ''; $link_attr .= ! empty( $data_object->url ) ? ' href="' . esc_attr( $data_object->url ) .'"' : ''; $link_attr .= " class=\"" . ( $current_object_id == $data_object->ID ? " active " : "" ) . str_replace( "color", $color, $a_class ) . "\" "; $output .= "
" . $post->post_content . "
"; } if ( $copyright ) { $html .= "" . wp_get_attachment_caption($attachment) . ""; } $html .= "" . esc_html($post->post_content) . "
"; } if ( $copyright ) { $html .= "" . esc_html(wp_get_attachment_caption($attachment)) . ""; } $html .= "" . $disclaimer . "
"; } return $html; } /** * Возвращает запрос WP_Query с выборкой для "читайте также" * @return WP_Query */ function read_another_posts() : WP_Query { $current_post_terms = wp_get_post_terms( get_the_ID(), ["post_tag", "category"], ["fields" => "id=>slug"] ); return new WP_Query( [ "post_type" => ["anew", "yellow"], "ignore_sticky_posts" => true, "posts_per_page" => 3, "order" => "DESC", "orderby" => "post_date", "post__not_in" => [ get_the_ID() ], "tax_query" => [ "relation" => "AND", [ "taxonomy" => "post_tag", "field" => "slug", "terms" => [ "aggregator" ], "operator" => in_array( "aggregator", $current_post_terms ) ? "IN" : "NOT IN" ] ] ] ); } /** * Возвращает html блока "Читайте также" * @return string */ function read_another_posts_block() : string { $posts = read_another_posts(); $html = ""; if( $posts->have_posts() ) { $html .= "" . read_another_posts_block(); array_splice($pharagraphs, 4, 0, $html); $content = implode( "
", $pharagraphs ); } return $content; } add_filter("the_content", "insert_read_another_posts_block", 99, 1); /** * Вставляет рекламные блоки в текст материала * @param string $content * @return string */ function insert_ads_to_post(string $content) : string { if ( is_single() && wp_is_mobile() && !get_post_gallery( get_queried_object_id() ) && !get_field("remove_ads") ) { $pharagraphs = explode("", $content); if ( get_post_type() === "profile_article" ) { $pharagraphs = array_reduce( array_map( function($i) { $html = load_template_part("template-parts/ad/adfox/ad-inread-" . rand(1, 3)); return count($i) == 3 ? array_merge($i, [$html]) : $i; }, array_chunk($pharagraphs, 3) ), function($r, $i) { return array_merge($r, $i); }, [] ); } else { $html = load_template_part("template-parts/ad/adfox/ad-inread-1"); array_splice($pharagraphs, 3, 0, $html); } return implode( "", $pharagraphs ); } return $content; } add_filter("the_content", "insert_ads_to_post", 99, 1); /** * Возвращает код темплейта * @param string $template_name * @param string $part_name * @param array $args * @return string */ function load_template_part( string $template_name = "", string $part_name = "", array $args = [] ) : string { ob_start(); get_template_part($template_name, $part_name, $args); return ob_get_clean(); } /** * Убирает первый параграф из текста материала * @param string $content * @return string */ function remove_first_pharagraph( string $content ) : string { if ( is_single() ) { $pharagraphs = explode("", $content); array_shift( $pharagraphs ); return implode( "", $pharagraphs ); } return $content; } /** * Вовзращает первый параграф материала * @param string $content * @return string */ function get_first_pharagraph( string $content ) : string { $content = wpautop( $content ); $pharagraphs = explode("", $content); $dom = new DOMDocument(); $dom->loadHTML('' . array_shift( $pharagraphs ) . ""); $links = $dom->getElementsByTagName('a'); foreach ($links as $link) { if ($link->getAttribute("redirect") == "true" && mb_strlen($link->getAttribute("href")) > 0) { $link->setAttribute("href", 'https://profile.ru/redirection?url=' . urlencode($link->getAttribute("href"))); $link->setAttribute("target", '_blank'); } } return str_replace(['', ''], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0))); } /** * Сжатие html */ require_once get_theme_file_path('/inc/compress-html.php'); //require_once 'inc/compress-html.php'; //require_once __DIR__ . "/inc/compress-html.php"; /** * Добавляет в крон хук, который сбрасывает кеш ALM на CDN * @param int $post_id * @return void */ function enqueue_purge_alm_cdn_cache( int $post_id ) : void { if( get_post_status() === "publish" && in_array( get_post_type(), ["anew", "profile_article", "yellow"] ) ) { wp_schedule_single_event( date("U"), "purge_alm_cdn_cache_action" ); } } add_action("save_post", "enqueue_purge_alm_cdn_cache", 999, 1); /** * Хук и функция сброса кеша ALM на CDN * @return void */ function purge_alm_cdn_cache () : void { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.selectel.ru/cdn/v2/projects/79a59227-6d80-4e33-863e-436820bf80ba/resources/20db689a-01bd-400d-b079-650896785b46/purge'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); $headers = []; $headers[] = 'X-Token: Cw2bGev0itdax2l6OUN3Ro3Aa_82810'; $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { error_log( 'Error:' . curl_error($ch) ); } curl_close($ch); } add_action("purge_alm_cdn_cache_action", "purge_alm_cdn_cache"); add_action("admin_init", "pauser"); /** * @return void * Привет соколову с его жирным "опять"! */ function pauser() : void { if(get_current_user_id() == 78 && $_SERVER["REMOTE_ADDR"] != "195.9.141.2") { sleep(3); } } /** * Проверяет, является ли строка валидным json * * @param $string * @return bool */ function isStringJson($string) { json_decode($string); return json_last_error() === JSON_ERROR_NONE; } add_filter("the_content", function($content){ if(is_feed()){ $url = $_SERVER["REQUEST_URI"]; $params = explode("/", $url); $params = array_filter($params); $gn = array_pop($params); if($gn === "gn"){ $content = "