1419 lines
39 KiB
PHP
1419 lines
39 KiB
PHP
<?php
|
||
|
||
/**
|
||
* TODO: Перед следующим релизом добавить фильтры:
|
||
* _hide_on_mainpage -- тут не забыть is_front_page() и https://connekthq.com/plugins/ajax-load-more/docs/filter-hooks/#alm_query_args
|
||
* _hide_on_website
|
||
* _only_link_access
|
||
*
|
||
* tax_query, который скроет с главной агрегатор
|
||
*
|
||
*
|
||
* TODO: Для мамлеева сделать отдельный cell (но обозвать его не мамлеев, а cell-only-title)
|
||
*
|
||
*
|
||
* TODO: Вывод галереи
|
||
*
|
||
*
|
||
*/
|
||
|
||
|
||
|
||
|
||
/**
|
||
* Подключение кастомных таблиц стилей (TODO: когда Ильгиз доделает, скачать, пока по ссылке)
|
||
*/
|
||
add_action( 'wp_enqueue_scripts', 'register_theme_styles' );
|
||
|
||
function register_theme_styles() : void
|
||
{
|
||
|
||
wp_register_style("main-styles", get_template_directory_uri() . "/assets/css/app.css", [], wp_get_theme()->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'] );
|
||
|
||
}
|
||
|
||
|
||
/**
|
||
* Добавление в 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);
|
||
$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 .= "<li class=\"" . ( $current_object_id == $data_object->ID ? " active " : "" ) . str_replace("color", $color, $li_class) . "\">";
|
||
|
||
$item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
|
||
$args->before,
|
||
$link_attr,
|
||
$args->link_before,
|
||
apply_filters( 'the_title', $data_object->title, $data_object->ID ),
|
||
$args->link_after,
|
||
$args->after
|
||
);
|
||
|
||
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $data_object, $depth, $args );
|
||
|
||
}
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
/**
|
||
* Проверяет наличие элементов массива в строке
|
||
* @param string $str
|
||
* @param array $arr
|
||
* @return bool
|
||
*/
|
||
function array_contains(string $str, array $arr) : bool
|
||
{
|
||
foreach ($arr as $a) {
|
||
if ( stripos($str, $a) !== false ) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
|
||
|
||
function replace_extension(string $filename, string $new_extension) : string
|
||
{
|
||
|
||
$info = pathinfo($filename);
|
||
|
||
return $info["dirname"] . "/" . $info["filename"] . "." . $new_extension;
|
||
|
||
}
|
||
|
||
/**
|
||
* Проверяет, установлен ли таймер и не истекло ли время показа заходного фото
|
||
* @param WP_Post|int|null $post
|
||
* @return bool
|
||
*/
|
||
function hide_thumbnail_by_countdown(WP_Post|int $post = null) : bool
|
||
{
|
||
$days = get_post_meta(get_the_ID(),'_hide_thumbnail_countdown', true);
|
||
|
||
if ( $days == NULL || $days <= 0 ) {
|
||
|
||
return false;
|
||
|
||
}
|
||
|
||
if( date("U") - get_the_date("U") > $days * 24 * 60 * 60 ) {
|
||
|
||
return true;
|
||
|
||
}
|
||
|
||
return false;
|
||
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* Проверяет, нужно ли показывать заходное фото
|
||
* @param WP_Post|int|null $post
|
||
* @return bool
|
||
*/
|
||
function show_post_thumbnail(WP_Post|int $post = null) : bool
|
||
{
|
||
|
||
$post_id = get_the_ID();
|
||
|
||
|
||
$days = get_post_meta(get_the_ID(),'_hide_thumbnail_countdown', true);
|
||
|
||
if ($days == 0){ // если ноль - показывать всегда
|
||
return true;
|
||
}
|
||
|
||
|
||
if( hide_thumbnail_by_countdown() ) {
|
||
|
||
return false;
|
||
|
||
}
|
||
|
||
//if ( is_single() || is_feed() ) {
|
||
|
||
if ( in_array( get_post_type(), ['anew', 'yellow'] ) && get_the_date("U") < 1719187200 ) {
|
||
|
||
$allow = [
|
||
"ТАСС",
|
||
"TASS",
|
||
"Профиль",
|
||
"Shutterstock"
|
||
];
|
||
|
||
$copyright = wp_get_attachment_caption( get_post_thumbnail_id() );
|
||
|
||
foreach ($allow as $c) {
|
||
|
||
if(str_contains($copyright, $c)) {
|
||
return true;
|
||
}
|
||
|
||
}
|
||
|
||
return false;
|
||
|
||
}
|
||
|
||
if ( get_post_type() === 'profile_article' && get_the_date("U") > 1577836800 ) {
|
||
return true;
|
||
}
|
||
|
||
$terms = get_the_category();
|
||
$term = array_shift($terms);
|
||
|
||
if(
|
||
$term->category_parent == 11430 ||
|
||
$term->term_id == 11430 ||
|
||
get_post_meta(get_the_ID(), 'event', true) == 1
|
||
|
||
) {
|
||
|
||
return true;
|
||
|
||
}
|
||
|
||
$allow = [
|
||
"Global Look Press",
|
||
"ТАСС",
|
||
"TASS",
|
||
"AFP",
|
||
"«Профиль»",
|
||
"kremlin.ru",
|
||
"president.gov.ua",
|
||
"president.gov.by",
|
||
"NASA",
|
||
"АГН «Москва»",
|
||
"АГН Москва",
|
||
"Агентство «Москва»",
|
||
"Авгурова",
|
||
"mil.ru",
|
||
"roscosmos.ru",
|
||
"mid.ru",
|
||
"vostock photo",
|
||
"duma.gov.ru",
|
||
"Пресс-служба"
|
||
];
|
||
|
||
$copyright = wp_get_attachment_caption( get_post_thumbnail_id() );
|
||
|
||
if( array_contains($copyright, $allow) ) {
|
||
|
||
return true;
|
||
|
||
}
|
||
|
||
if( date("U") - ( get_the_date("U") ) > 10 * 24 * 60 * 60 ) {
|
||
|
||
return false;
|
||
|
||
}
|
||
|
||
return true;
|
||
|
||
//}
|
||
|
||
return true;
|
||
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* * TODO:Зарефакторить
|
||
* Переписывает html вывода заходного фото постов
|
||
* @param string $html
|
||
* @param int $post_id
|
||
* @param int $post_thumbnail_id
|
||
* @return string
|
||
*/
|
||
function post_thumbnail_html_override( string $html, int $post_id, int $post_thumbnail_id, $size = "post-shumbnail", array|string $attr = "") : string
|
||
{
|
||
|
||
if( is_admin() || !in_array( get_post_type( $post_id ), ["anew", "yellow", "profile_article"] ) ) {
|
||
|
||
return $html;
|
||
|
||
}
|
||
|
||
return wp_get_attachment_image_html($post_thumbnail_id, true, true);
|
||
|
||
}
|
||
add_filter( 'post_thumbnail_html', 'post_thumbnail_html_override', 999, 5 );
|
||
|
||
|
||
|
||
|
||
/**
|
||
* * TODO:Зарефакторить
|
||
* Переписывает html вывода аватара автора
|
||
* @param string $html
|
||
* @param int $post_id
|
||
* @param int $post_thumbnail_id
|
||
* @return string
|
||
*/
|
||
function author_thumbnail_html_override( string $html, int $post_id, int $post_thumbnail_id, array|int|string $size = "post-shumbnail", array|string $attr = "") : string
|
||
{
|
||
|
||
if( is_admin() || !in_array( get_post_type( $post_id ), ["guest-author"] ) ) {
|
||
|
||
return $html;
|
||
|
||
}
|
||
|
||
$html = "<figure itemprop=\"image\" itemscope itemtype=\"https://schema.org/ImageObject\">";
|
||
|
||
$html .= "<picture class=\"onenews__picture\">";
|
||
|
||
$src = wp_get_attachment_image_src($post_thumbnail_id, "thumbnail")[0];
|
||
$src = $src ? $src : get_template_directory_uri() . "/assets/img/placeholder-264-264.png";
|
||
|
||
$mime = wp_get_image_mime($src);
|
||
|
||
$html .= "<source srcset=\"" . $src . "\" type=\"" . $mime . "\" media=\"all\" />";
|
||
|
||
$html .= "
|
||
<img
|
||
class=\"d-inline author__img\"
|
||
loading=\"lazy\"
|
||
width=\"264\"
|
||
height=\"264\"
|
||
src=\"" . $src . "\"
|
||
alt=\"" . get_post_meta($post_id, '_wp_attachment_image_alt', true) . "\" />
|
||
";
|
||
|
||
$html .= "<link itemprop=\"url\" href=\"" . $src . "\" />";
|
||
$html .= "<link itemprop=\"contentUrl\" href=\"" . $src . "\" />";
|
||
|
||
$html .= "</picture>";
|
||
|
||
$html .= "</figure>";
|
||
|
||
return $html;
|
||
|
||
}
|
||
add_filter( 'post_thumbnail_html', 'author_thumbnail_html_override', 998, 5 );
|
||
|
||
|
||
/**
|
||
* TODO:Зарефакторить
|
||
* Изменение html для изображений
|
||
* @param WP_Post|int $attachment
|
||
* @param bool $caption
|
||
* @param bool $copyright
|
||
* @param int $max_size
|
||
* @return string
|
||
*/
|
||
function wp_get_attachment_image_html_720( WP_Post|int $attachment = 0, bool $caption = false, bool $copyright = false, int $max_size = 782 ) : string
|
||
{
|
||
|
||
$post = get_post($attachment);
|
||
|
||
$html = "<figure itemprop=\"image\" itemscope itemtype=\"https://schema.org/ImageObject\">";
|
||
|
||
$html .= "<picture class=\"onenews__picture\">";
|
||
|
||
$sizes = [
|
||
320 => 350,
|
||
400 => 430,
|
||
500 => 530,
|
||
590 => 620,
|
||
782 => 768,
|
||
1200 => 768
|
||
];
|
||
|
||
foreach ($sizes as $size => $media) {
|
||
|
||
if($size > $max_size) { continue; }
|
||
|
||
$media = "(" . ($size < $max_size ? "max" : "min") . "-width: " . $media . ")";
|
||
|
||
$src = wp_get_attachment_image_src($attachment, "thumb-".$size)[0];
|
||
$src = $src ? $src : get_template_directory_uri() . "/assets/img/placeholder-782-440.png";
|
||
$mime = wp_get_image_mime($src);
|
||
|
||
$html .= "<source srcset=\"" . $src . "\" type=\"" . $mime . "\" media=\"" . $media . "\" />";
|
||
|
||
}
|
||
|
||
$html .= "
|
||
<img
|
||
class=\"d-block\"
|
||
width=\"" . ( wp_is_mobile() ? 500 : 1200 ) . "\"
|
||
height=\"" . ( wp_is_mobile() ? 281 : 675 ) . "\"
|
||
src=\"" . ( wp_is_mobile() ? wp_get_attachment_image_src($attachment, "thumb-500")[0] : $src ) . "\"
|
||
alt=\"" . get_post_meta($attachment, '_wp_attachment_image_alt', true) . "\" />
|
||
";
|
||
|
||
|
||
|
||
$html .= "<link itemprop=\"url\" href=\"" . $src . "\" />";
|
||
$html .= "<link itemprop=\"contentUrl\" href=\"" . $src . "\" />";
|
||
|
||
$html .= "</picture>";
|
||
|
||
if ( $caption || $copyright ) {
|
||
|
||
$html .= "<figcaption>";
|
||
|
||
if ( $caption ) {
|
||
|
||
$html .= "<p>" . $post->post_content . "</p>";
|
||
|
||
}
|
||
|
||
if ( $copyright ) {
|
||
|
||
$html .= "<span>" . wp_get_attachment_caption($attachment) . "</span>";
|
||
|
||
}
|
||
|
||
$html .= "</figcaption>";
|
||
|
||
}
|
||
|
||
|
||
$html .= "</figure>";
|
||
|
||
return $html;
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
/**
|
||
* * TODO:Зарефакторить
|
||
* Добавляем <link rel="preload" as="image" href="" /> в head
|
||
*/
|
||
add_action("wp_head", function() {
|
||
|
||
if( !is_single() || !has_post_thumbnail() ) {
|
||
|
||
return;
|
||
|
||
}
|
||
|
||
$post = get_post();
|
||
|
||
$attachment = get_post_thumbnail_id( $post );
|
||
|
||
$sizes = [
|
||
320 => 350,
|
||
400 => 430,
|
||
500 => 530,
|
||
590 => 620,
|
||
782 => 768,
|
||
1200 => 768
|
||
];
|
||
|
||
foreach ($sizes as $size => $media) {
|
||
|
||
$src = wp_get_attachment_image_src($attachment, "thumb-".$size)[0];
|
||
$src = $src ? $src : get_template_directory_uri() . "/assets/img/placeholder-782-440.png";
|
||
|
||
echo "<link rel=\"preload\" as=\"image\" href=\"" . $src . "\" media=\"" . $media . "\" />";
|
||
|
||
}
|
||
|
||
|
||
|
||
});
|
||
|
||
function wp_get_attachment_image_html( WP_Post|int $attachment = 0, bool $caption = false, bool $copyright = false, int $max_size = 1200 ) : string
|
||
{
|
||
$post = get_post($attachment);
|
||
|
||
// Получаем изображение 1200px
|
||
$img_1200 = wp_get_attachment_image_src($attachment, 'thumb-1200');
|
||
$img_1200_src = $img_1200 ? $img_1200[0] : get_template_directory_uri() . "/assets/img/placeholder-1200-675.png";
|
||
$img_alt = esc_attr(get_post_meta($attachment, '_wp_attachment_image_alt', true));
|
||
|
||
$html = "<figure itemprop=\"image\" itemscope itemtype=\"https://schema.org/ImageObject\">";
|
||
$html .= "<picture class=\"onenews__picture\">";
|
||
|
||
// Массив размеров для <source>
|
||
$sizes = [
|
||
320 => 350,
|
||
400 => 430,
|
||
500 => 530,
|
||
590 => 620,
|
||
782 => 768,
|
||
1200 => 1024 // media breakpoint, не обязательно точно 1200px
|
||
];
|
||
|
||
foreach ($sizes as $size => $media_width) {
|
||
if ($size > $max_size) {
|
||
continue;
|
||
}
|
||
|
||
$media_query = "(" . ($size < $max_size ? "max" : "min") . "-width: " . $media_width . "px)";
|
||
$source_img = wp_get_attachment_image_src($attachment, "thumb-" . $size);
|
||
$src = $source_img ? $source_img[0] : get_template_directory_uri() . "/assets/img/placeholder-{$size}.png";
|
||
$mime = wp_get_image_mime($src);
|
||
|
||
$html .= "<source srcset=\"" . esc_url($src) . "\" type=\"" . esc_attr($mime) . "\" media=\"" . esc_attr($media_query) . "\" />";
|
||
}
|
||
|
||
// Основное изображение на desktop — 1200px
|
||
$html .= "
|
||
<img
|
||
class=\"d-block\"
|
||
width=\"1200\"
|
||
height=\"675\"
|
||
src=\"" . esc_url($img_1200_src) . "\"
|
||
alt=\"" . $img_alt . "\" />
|
||
";
|
||
|
||
$html .= "<link itemprop=\"url\" href=\"" . esc_url($img_1200_src) . "\" />";
|
||
$html .= "<link itemprop=\"contentUrl\" href=\"" . esc_url($img_1200_src) . "\" />";
|
||
|
||
$html .= "</picture>";
|
||
|
||
// Добавим caption и/или copyright
|
||
if ( $caption || $copyright ) {
|
||
$html .= "<figcaption>";
|
||
if ( $caption ) {
|
||
$html .= "<p>" . esc_html($post->post_content) . "</p>";
|
||
}
|
||
if ( $copyright ) {
|
||
$html .= "<span>" . esc_html(wp_get_attachment_caption($attachment)) . "</span>";
|
||
}
|
||
$html .= "</figcaption>";
|
||
}
|
||
|
||
$html .= "</figure>";
|
||
|
||
return $html;
|
||
}
|
||
|
||
|
||
|
||
|
||
/**
|
||
* Добавляет символ © к подписи к фотографии
|
||
* @param string $caption
|
||
* @return string
|
||
*/
|
||
function add_copyright_to_caption( string $caption ) : string
|
||
{
|
||
|
||
return "©" . str_replace("©", "", $caption);
|
||
|
||
}
|
||
add_filter("wp_get_attachment_caption", "add_copyright_to_caption", 20, 1);
|
||
|
||
|
||
|
||
/**
|
||
* Фильтр для depositphotos, превращает строку depositphotos в ссылку на depositphotos.com в соответствии с условиями пользовательского соглашения
|
||
* @param string $caption
|
||
* @return string
|
||
*/
|
||
function depositphotos_link_to_caption( string $caption ) : string
|
||
{
|
||
|
||
return str_ireplace('depositphotos.com', '<a target="_blank" href="https://depositphotos.com/">depositphotos.com</a>', $caption);
|
||
|
||
}
|
||
add_filter("wp_get_attachment_caption", "depositphotos_link_to_caption", 30, 1);
|
||
|
||
|
||
/**
|
||
* Проверяет, относится ли страница к спецпроекту
|
||
* @return bool
|
||
*/
|
||
function is_special() : bool
|
||
{
|
||
|
||
if( is_tag() || is_category() ) {
|
||
|
||
return
|
||
get_term_meta( get_queried_object_id(), "type", true ) === "special"
|
||
||
|
||
get_term_meta( get_queried_object()->parent, "type", true ) === "special";
|
||
|
||
}
|
||
|
||
if ( is_single() ) {
|
||
|
||
return
|
||
get_term_meta( get_the_category( get_queried_object_id() )[0]->term_id, 'type', true) === "special"
|
||
||
|
||
get_term_meta( get_the_category( get_queried_object_id() )[0]->parent, 'type', true) === "special";
|
||
|
||
}
|
||
|
||
return false;
|
||
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* Возвращает строку со слагом категории-спецпроекта
|
||
* @return string
|
||
*/
|
||
function get_special_slug() : string
|
||
{
|
||
|
||
if( is_tag() || is_category() ) {
|
||
|
||
return get_queried_object()->slug;
|
||
|
||
}
|
||
|
||
if ( is_single() ) {
|
||
|
||
return get_the_category( get_queried_object_id() )[0]->slug;
|
||
|
||
}
|
||
|
||
return "";
|
||
}
|
||
|
||
|
||
/**
|
||
* Генерирует и возвращает идентификатор кеша ajax-load-mode
|
||
* @return int
|
||
*/
|
||
function get_alm_cache_id( mixed $after = "" ) : int
|
||
{
|
||
|
||
$current_id = get_queried_object_id();
|
||
$mobile = (int)wp_is_mobile();
|
||
$last_id = 0;
|
||
|
||
$last_id_query = new WP_Query(
|
||
[
|
||
"ignore_sticky_posts" => true,
|
||
"suppress_filters" => true,
|
||
"post_type" => ["profile_article", "anew", "yellow", "page", "archive", "guest-author"],
|
||
"posts_per_page" => 1,
|
||
"orderby" => "id",
|
||
"order" => "DESC"
|
||
]
|
||
);
|
||
|
||
if( $last_id_query->have_posts() ) {
|
||
|
||
while( $last_id_query->have_posts() ) {
|
||
|
||
$last_id_query->the_post();
|
||
|
||
$last_id = get_the_ID();
|
||
|
||
}
|
||
|
||
}
|
||
|
||
wp_reset_postdata();
|
||
|
||
return (int)( $current_id.$mobile.$last_id.$after );
|
||
|
||
//return (int) ( date("U") . $current_id.$mobile.$last_id.$after );
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
/**
|
||
* Регистрирует адресное пространство /events/?..., добавляет правило рерайта для него и переменную is_event
|
||
* @return void
|
||
*/
|
||
function register_events_slug() : void
|
||
{
|
||
|
||
add_rewrite_tag( '%is_event%', '([^&]+)' );
|
||
|
||
add_rewrite_rule( '^/(events)?','index.php?post_type=anew&is_event=true', 'top' );
|
||
|
||
flush_rewrite_rules();
|
||
|
||
}
|
||
add_action("init", "register_events_slug");
|
||
|
||
|
||
|
||
/**
|
||
* Проверка нахождения в индексе событий
|
||
* @return bool
|
||
*/
|
||
function is_events() : bool
|
||
{
|
||
|
||
return !!get_query_var("is_event");
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
/**
|
||
* Фильтр и сортировка для страницы событий
|
||
* @param WP_Query|null $query
|
||
* @return WP_Query
|
||
*/
|
||
function filter_events( WP_Query $query = null ) : WP_Query
|
||
{
|
||
|
||
if( is_events() && $query->is_main_query() ) {
|
||
|
||
$query->set(
|
||
"meta_query",
|
||
[
|
||
"relation" => "AND",
|
||
"order_clause" => [
|
||
"key" => "event_date",
|
||
"type" => "DATE"
|
||
],
|
||
"key_clause" => [
|
||
"key" => "event",
|
||
"value" => "1",
|
||
"compare" => "="
|
||
]
|
||
]
|
||
);
|
||
$query->set( "order", "DESC" );
|
||
$query->set( "orderby", "order_clause" );
|
||
|
||
}
|
||
|
||
|
||
|
||
return $query;
|
||
|
||
}
|
||
add_filter("pre_get_posts", "filter_events", 20, 1);
|
||
|
||
|
||
/**
|
||
* Добавляет микроразметку в хлебные крошки rank math
|
||
* @param string $html
|
||
* @param array $crumbs
|
||
* @return string
|
||
*/
|
||
function breadcrumbs_microdata(string $html, array $crumbs) : string
|
||
{
|
||
|
||
$html = "<ol class=\"d-none\" itemscope itemtype=\"https://schema.org/BreadcrumbList\">";
|
||
|
||
foreach ( $crumbs as $i => $crumb ) {
|
||
|
||
$html .= "<li itemprop=\"itemListElement\" itemscope itemtype=\"https://schema.org/ListItem\">";
|
||
|
||
$html .= "<a itemprop=\"item\" href=\"" . str_replace("admin.", "", $crumb[1]) . "\">";
|
||
|
||
$html .= "<span itemprop=\"name\">" . $crumb[0] . "</span>";
|
||
|
||
$html .= "<meta itemprop=\"position\" content=\"" . ( $i + 1 ) . "\" />";
|
||
|
||
$html .= "</a>";
|
||
|
||
$html .= "</li>";
|
||
|
||
}
|
||
|
||
$html .= "</ol>";
|
||
|
||
return $html;
|
||
|
||
}
|
||
add_filter( "rank_math/frontend/breadcrumb/html", "breadcrumbs_microdata", 10, 2);
|
||
|
||
|
||
/**
|
||
* Возвращает html-код дисклеймера, если он был указан в свойствах термина таксономии
|
||
* @return string
|
||
*/
|
||
function get_disclaimer() : string
|
||
{
|
||
|
||
$disclaimers = [];
|
||
$html = "";
|
||
|
||
foreach ( wp_get_post_terms( get_the_ID(), ["post_tag", "category"] ) as $term ) {
|
||
|
||
$meta = get_term_meta( $term->term_id, "disclaimer", true );
|
||
|
||
if ( $meta ) {
|
||
|
||
$disclaimers[] = $meta;
|
||
|
||
}
|
||
|
||
}
|
||
|
||
array_unique( $disclaimers );
|
||
|
||
foreach ( $disclaimers as $disclaimer ) {
|
||
|
||
$html .= "<p class=\"attention\">" . $disclaimer . "</p>";
|
||
|
||
}
|
||
|
||
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 .= "<div id=\"readanother\">";
|
||
|
||
$html .= "<strong>Читайте также:</strong>";
|
||
|
||
$html .= "<ul>";
|
||
|
||
while( $posts->have_posts() ) {
|
||
|
||
$posts->the_post();
|
||
|
||
$html .= "<li>";
|
||
|
||
$html .= "<a href=\"" . get_the_permalink() . "?utm_from=readmore\">" . get_the_title() . "</a>";
|
||
|
||
$html .= "</li>";
|
||
|
||
}
|
||
|
||
$html .= "</ul>";
|
||
|
||
$html .= "</div>";
|
||
|
||
|
||
}
|
||
|
||
wp_reset_postdata();
|
||
|
||
return $html;
|
||
|
||
}
|
||
|
||
/**
|
||
* Вставляет в тело материала блок "Читайте также"
|
||
* @param string $content
|
||
* @return string
|
||
*/
|
||
function insert_read_another_posts_block( string $content ) : string
|
||
{
|
||
|
||
if ( wp_is_mobile() && !is_admin() && in_array( get_post_type() , ['anew', 'profile_article'] ) ) {
|
||
|
||
$pharagraphs = explode("</p>", $content);
|
||
|
||
$html = "<p>" . read_another_posts_block();
|
||
|
||
array_splice($pharagraphs, 4, 0, $html);
|
||
|
||
$content = implode( "</p>", $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("</p>", $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( "</p>", $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("</p>", $content);
|
||
|
||
array_shift( $pharagraphs );
|
||
|
||
return implode( "</p>", $pharagraphs );
|
||
|
||
}
|
||
|
||
return $content;
|
||
|
||
}
|
||
|
||
/**
|
||
* Вовзращает первый параграф материала
|
||
* @param string $content
|
||
* @return string
|
||
*/
|
||
function get_first_pharagraph( string $content ) : string
|
||
{
|
||
|
||
$content = wpautop( $content );
|
||
|
||
$pharagraphs = explode("</p>", $content);
|
||
|
||
|
||
$dom = new DOMDocument();
|
||
$dom->loadHTML('<?xml encoding="utf-8" ?>' . array_shift( $pharagraphs ) . "</p>");
|
||
|
||
$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(['<body>', '</body>'], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0)));
|
||
|
||
|
||
|
||
}
|
||
|
||
|
||
/**
|
||
* Сжатие html
|
||
*/
|
||
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 = "<h1>" . get_the_title( get_the_ID() ) . "</h1>" . $content;
|
||
|
||
}
|
||
|
||
}
|
||
|
||
return $content;
|
||
|
||
}, PHP_INT_MAX);
|
||
|
||
|
||
add_filter("pre_get_posts", function($query){
|
||
|
||
if(is_feed() && str_contains($_SERVER["REQUEST_URI"], "/zen")){
|
||
|
||
$query->set(
|
||
"meta_query", [
|
||
"relation" => "AND",
|
||
[
|
||
"meta_key" => "yzrssenabled_meta_value",
|
||
"meta_value" => "yes",
|
||
"compare" => "!="
|
||
]
|
||
]
|
||
);
|
||
|
||
|
||
}
|
||
|
||
return $query;
|
||
}, PHP_INT_MAX); |