add block-cache-manager.php

This commit is contained in:
Andrey Kuvshinov
2025-08-27 00:00:02 +03:00
parent b5595ae76e
commit f3314894aa
12 changed files with 339 additions and 100 deletions

112
block-cache-manager.php Normal file
View File

@@ -0,0 +1,112 @@
<?php
/**
* Кеширующая обертка для get_template_part()
*
* @param string $template Путь к шаблону
* @param string $name Имя шаблона (необязательно)
* @param array $data Данные для передачи в шаблон
* @param int $expire Время жизни кеша в секундах
* @return void
*/
function cached_get_template_part( $template, $name = null, $data = [] ) {
$fcache = CACHED_TEMPLATE.$template.'.html';
if ( file_exists($fcache) ){
echo file_get_contents($fcache);
return true;
}
$file_directory = dirname($fcache);
ob_start();
get_template_part($template, $name, $data );
$content = ob_get_clean();
echo $content;
if (!file_exists($file_directory)) {
if (!wp_mkdir_p($file_directory)) {
error_log('Не удалось создать директорию: ' . $file_directory);
return false;
}
}
if (false === file_put_contents($fcache, $content)) {
error_log('Не удалось сохранить файл: ' . $fcache);
return false;
}
return true;
}
// Функция очистки кеша
function clear_template_cache ( $template ) {
$cache_file = CACHED_TEMPLATE.$template.'.html';
if (file_exists($cache_file)) {
return unlink($cache_file);
}
}
/**
* Общая функция для сброса кеша на основе условий поста
*
* @param WP_Post $post Объект поста (уже содержит ID)
*/
function clear_post_cache_based_on_conditions( $post_id, $post ) {
// Кеш по типу поста
if ($post->post_type == 'profile_article') {
clear_template_cache('template-parts/home/list-items');
clear_template_cache('template-parts/home/main-item');
clear_template_cache('template-parts/home/colon-item');
} elseif ($post->post_type == 'anew' || $post->post_type == 'yellow') {
clear_template_cache('template-parts/home/news');
}
// Сброс главной
$main_item = get_post_meta($post_id, 'main_item', true);
if ($main_item === 'true' || $main_item === '1') {
clear_template_cache('template-parts/home/main-item');
}
// Сброс колонки
$colon_item = get_post_meta($post_id, 'colon_item', true);
if ($colon_item === 'true' || $colon_item === '1') {
clear_template_cache('template-parts/home/colon-item');
}
}
// Хук для обычного сохранения
add_action('save_post', function($post_id, $post, $update) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
if (!current_user_can('edit_post', $post_id)) return;
if ($post->post_status !== 'publish') return;
clear_post_cache_based_on_conditions($post_id, $post); // Передаем только $post
}, 10, 3);
// Хук для запланированных публикаций
add_action('transition_post_status', function($new_status, $old_status, $post) {
if ($new_status !== 'publish') return;
if (!current_user_can('edit_post', $post->ID)) return; // Используем $post->ID
clear_post_cache_based_on_conditions($post->ID, $post); // Передаем только $post
}, 10, 3);
?>

View File

@@ -414,13 +414,23 @@
function show_post_thumbnail(WP_Post|int $post = null) : 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() ) { if( hide_thumbnail_by_countdown() ) {
return false; return false;
} }
if ( is_single() || is_feed() ) { //if ( is_single() || is_feed() ) {
if ( in_array( get_post_type(), ['anew', 'yellow'] ) && get_the_date("U") < 1719187200 ) { if ( in_array( get_post_type(), ['anew', 'yellow'] ) && get_the_date("U") < 1719187200 ) {
@@ -501,7 +511,7 @@
return true; return true;
} //}
return true; return true;
@@ -1279,7 +1289,8 @@
/** /**
* Сжатие html * Сжатие html
*/ */
require_once __DIR__ . "/inc/compress-html.php"; require_once 'inc/compress-html.php';
//require_once __DIR__ . "/inc/compress-html.php";

View File

@@ -1,12 +1,13 @@
<?php <?php
//ini_set('display_errors', 1); ini_set('display_errors', 1);
//error_reporting(E_ERROR); error_reporting(E_ERROR);
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
require "clear-functions.php"; require get_theme_file_path('clear-functions.php');
require "dirty-functions.php"; require "dirty-functions.php";
require "garbage-functions.php"; require "garbage-functions.php";
require "block-cache-manager.php"; //кешируем долгоживущие блоки
include "inc/get_cached_alm.php"; include "inc/get_cached_alm.php";
//TODO: Убрать все эти is_yn, is_zen и прочее и внутри плагинов регулировать вывод //TODO: Убрать все эти is_yn, is_zen и прочее и внутри плагинов регулировать вывод
@@ -27,11 +28,16 @@ define( 'AUTOMATIC_UPDATER_DISABLED', true );
// Отключаем только обновления ядра // Отключаем только обновления ядра
define( 'WP_AUTO_UPDATE_CORE', false ); define( 'WP_AUTO_UPDATE_CORE', false );
//кеш блоков
define('CACHED_TEMPLATE', trailingslashit( wp_upload_dir()['basedir'] ) . 'cached_template/');
// Отключаем обновления плагинов и тем // Отключаем обновления плагинов и тем
add_filter( 'auto_update_plugin', '__return_false' ); add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' ); add_filter( 'auto_update_theme', '__return_false' );
//debug //debug
/** /**
@@ -600,7 +606,26 @@ add_filter("the_content", function($content){
/**
* Исправляет битые ссылки с одним слэшем после https:/ и добавляет домен.
*
* @param string $url Битая ссылка.
* @param string $domain Домен (без слэша в конце, например "example.com").
* @return string Исправленная ссылка.
*/
function fix_broken_url($url, $domain) {
// Удаляем лишние пробелы
$url = trim($url);
// Если ссылка начинается с https:/ и нет второго слэша — исправляем
if (preg_match('#^https:/([^/].*)#i', $url, $matches)) {
// Добавляем правильный https:// и домен
return 'https://' . $domain . '/' . ltrim($matches[1], '/');
}
// Если ссылка уже правильная, возвращаем как есть
return $url;
}
@@ -998,7 +1023,27 @@ add_action('admin_enqueue_scripts', 'admin_style');
add_action('wp_enqueue_scripts', 'admin_style'); add_action('wp_enqueue_scripts', 'admin_style');
//дополнительные стили и скрипты
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( //добавляем корректор времени
'moscow-date',
get_template_directory_uri() . '/assets/js/moscow-date.js',
array(), // зависимости
filemtime(get_template_directory() . '/assets/js/moscow-date.js'), // версия
true // в футере
);
// Добавляем стиль
wp_enqueue_style(
'profile-style', // уникальный идентификатор
get_template_directory_uri() . '/assets/css/profile-style.css', // путь к файлу
array(), // зависимости
filemtime(get_template_directory() . '/assets/css/profile-style.css') // версия
);
});
@@ -2069,8 +2114,8 @@ function custom_field_html($field){
<input <input
type="checkbox" type="checkbox"
value="'.$field['value'].'" value="'.$field['value'].'"
name="' . $field['id'] . ' " name="' . $field['id'] . '"
' . checked((bool)$value, true) . ' ' . checked((bool)$value, true, false) . '
/> />
' . _e($field['label']); ' . _e($field['label']);
break; break;
@@ -2263,6 +2308,30 @@ remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'rsd_link' ); remove_action( 'wp_head', 'rsd_link' );
//делаем opengraph для постов без фото
add_action('wp_head', function() {
if (!is_singular()) return;
$post_id = get_the_ID();
$default_image = 'https://cdn.profile.ru/wp-content/uploads/2023/07/profile_lazyload_hq.jpg'; // Заглушка в папке темы
$og_image = esc_url($default_image);
if (!has_post_thumbnail($post_id) or !show_thumbnail($post_id)) {
echo '<meta property="og:image" content="' . $og_image . '" />' . "\n";
echo '<meta property="og:image:width" content="1200" />' . "\n";
echo '<meta property="og:image:height" content="630" />' . "\n";
echo '<meta name="twitter:image" content="' . $og_image . '" />';
//} else {
// $og_image = get_the_post_thumbnail_url($post_id, 'large');
}
});
//Добавили к ссылкам nofollow //Добавили к ссылкам nofollow
@@ -2962,11 +3031,21 @@ function send_telegram($post) {
$bot_id = "1108783670:AAGm7_vdXQAte25OGUa5gWJNXhy5-v6d_hU"; $bot_id = "1108783670:AAGm7_vdXQAte25OGUa5gWJNXhy5-v6d_hU";
$post_id = (is_object($post_id)) ? $post_id->ID : $post_id; $post_id = (is_object($post_id)) ? $post_id->ID : $post_id;
// Получаем и проверяем ссылку
$curr_url = get_permalink($post_id);
if (empty($curr_url)) {
error_log('Telegram bot: Empty permalink for post ID ' . $post_id);
return;
}
$curr_url = fix_broken_url($curr_url, 'profile.ru'); //корректируем ссылку с ошиюбками
if(has_tag(103565, $post_id)){ if(has_tag(103565, $post_id)){
$chat_id = "-1001241573514";//идентификатор канала profile_lifestyle $chat_id = "-1001241573514";//идентификатор канала profile_lifestyle
$text = '<a href="' . get_the_permalink($post_id) . '?utm_from=telegram">' . get_the_title($post_id) . '</a>';
$text = '<a href="' . $curr_url . '?utm_from=telegram">' . get_the_title($post_id) . '</a>';
$text = str_replace('admin.', '', $text); $text = str_replace('admin.', '', $text);
$request = "https://api.telegram.org/bot" . $bot_id . "/sendMessage?chat_id=" . $chat_id . "&parse_mode=HTML&text=" . urlencode($text); $request = "https://api.telegram.org/bot" . $bot_id . "/sendMessage?chat_id=" . $chat_id . "&parse_mode=HTML&text=" . urlencode($text);
@@ -2976,6 +3055,8 @@ function send_telegram($post) {
curl_setopt($ch, CURLOPT_URL, $request); curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); $result = curl_exec($ch);
}else{ }else{
if( if(
(((bool)filter_input(INPUT_POST,'_send_telegram')) (((bool)filter_input(INPUT_POST,'_send_telegram'))
@@ -2985,7 +3066,7 @@ function send_telegram($post) {
$chat_id = "-1001365682276";//идентификатор канала profile_news $chat_id = "-1001365682276";//идентификатор канала profile_news
$text = '<a href="'.get_the_permalink($post_id).'?utm_from=telegram">'.get_the_title($post_id).'</a>'; $text = '<a href="'.$curr_url.'?utm_from=telegram">'.get_the_title($post_id).'</a>';
$text = str_replace('admin.', '', $text); $text = str_replace('admin.', '', $text);
$request = "https://api.telegram.org/bot".$bot_id."/sendMessage?chat_id=".$chat_id."&parse_mode=HTML&text=".urlencode($text); $request = "https://api.telegram.org/bot".$bot_id."/sendMessage?chat_id=".$chat_id."&parse_mode=HTML&text=".urlencode($text);
@@ -6129,8 +6210,17 @@ add_filter( 'ep_post_sync_kill', 'my_ep_stop_sync', 10, 3 );*/
add_action('wp_insert_post', 'news_telegram_log', 10, 1 ); add_action('wp_insert_post', 'news_telegram_log', 10, 1 );
//хук для запланированных
add_action('transition_post_status', function($new_status, $old_status, $post) {
if ($new_status == 'publish' && $old_status == 'future') {
news_telegram_log($post);
}
}, 10, 3);
function news_telegram_log($post){ function news_telegram_log($post){
$post = get_post($post); $post = get_post($post);
@@ -6147,15 +6237,20 @@ function news_telegram_log($post){
return; return;
} }
if(wp_get_post_categories($post_id)[0] == 104862){ if(wp_get_post_categories($post_id)[0] == 104862){
return; return;
} }
// Получаем и проверяем ссылку
$curr_link = get_permalink($post_id);
if (empty($curr_link)) {
error_log('Telegram bot: Empty permalink for post ID ' . $post_id);
return;
}
$curr_link = fix_broken_url($curr_link, 'profile.ru'); //корректируем ссылку с ошиюбками
$content = '<a href="'.get_the_permalink($post_id).'?utm_from=telegram">'.get_the_title($post_id).'</a>'; $content = '<a href="'.$curr_link.'?utm_from=telegram">'.get_the_title($post_id).'</a>';
$content = str_replace('admin.', '', $content); $content = str_replace('admin.', '', $content);
$request = "https://api.telegram.org/bot1184440628:AAE5N10dnzClx3Qce4v1mBD9ax1BsHo98Rs/sendMessage?chat_id=-1001588455134&parse_mode=HTML&text=".urlencode($content); $request = "https://api.telegram.org/bot1184440628:AAE5N10dnzClx3Qce4v1mBD9ax1BsHo98Rs/sendMessage?chat_id=-1001588455134&parse_mode=HTML&text=".urlencode($content);
@@ -6207,6 +6302,13 @@ function show_thumbnail($id = false) : bool
$id = get_the_ID(); $id = get_the_ID();
} }
// НОВОЕ УСЛОВИЕ: Амнистия для постов, опубликованных после 1 августа 2025 года
$amnestyDate = strtotime('2025-08-01');
if (get_the_date("U", $id) > $amnestyDate) {
return true;
}
$days = ((get_post_meta($id,'_hide_thumbnail_countdown'))[0]); $days = ((get_post_meta($id,'_hide_thumbnail_countdown'))[0]);
if ( $days == NULL ){ if ( $days == NULL ){

View File

@@ -7,7 +7,7 @@
alt="<?= htmlspecialchars( get_the_title() ) ?>" alt="<?= htmlspecialchars( get_the_title() ) ?>"
/> />
<?php else : ?> <?php else : //1361306 ?>
<img loading="lazy" <img loading="lazy"
src="<?= wp_get_attachment_image_url( 1357368, $args["wide"] && !wp_is_mobile() ? "large" : "post-thumbnail"); ?>" src="<?= wp_get_attachment_image_url( 1357368, $args["wide"] && !wp_is_mobile() ? "large" : "post-thumbnail"); ?>"

View File

@@ -1,6 +1,8 @@
<!--[archive/list]--> <!--[archive/list]-->
<?php global $wp_query; ?> <?php global $wp_query;
$sql_query = $wp_query->request;
echo $sql_query; // Выведет SQL-запрос?>
<?php if( have_posts() ) : ?> <?php if( have_posts() ) : ?>

View File

@@ -4,7 +4,7 @@
<div class="container-fluid clearfix"> <div class="container-fluid clearfix">
<div class="row d-flex flex-row"> <div class="row d-flex flex-row">
<div class="col-12 col-sm-2 col-xl-3"> <div class="col-12 col-sm-2 col-xl-3">
<span class="font-weight-bold"> <span class="font-weight-bold" id="current-date">
<?= date_i18n('j F Y') ?> <?= date_i18n('j F Y') ?>
</span> </span>
</div> </div>

View File

@@ -51,12 +51,14 @@
<?php get_template_part("template-parts/header/breadcrumbs") ?> <?php get_template_part("template-parts/header/breadcrumbs") ?>
<?php if(!wp_is_mobile()) : ?>
<?php if( !wp_is_mobile() and is_home() ) : ?>
<div style="margin-bottom: 18px; text-align: center;"> <div style="margin-bottom: 18px; text-align: center;">
<?php get_template_part("template-parts/ad/revive/ad", "", [ "zone" => 14, "show_on_mobile" => false ]); ?> <?php get_template_part("template-parts/ad/revive/ad", "", [ "zone" => 12, "show_on_mobile" => false ]); ?>
</div> </div>
<?php endif; ?> <?php endif; ?>
<div class="container-fluid"> <div class="container-fluid">

View File

@@ -36,14 +36,7 @@ $colon_query = new WP_Query(
<div class="d-flex" > <div class="d-flex" >
<div class="blog" <div class="blog">
itemscope
<?php if( get_post_type() == "profile_article"): ?>
itemtype="https://schema.org/Article"
<?php else: ?>
itemtype="https://schema.org/NewsArticle"
<?php endif; ?>
>
<a class="blog__frame" href="<?= the_permalink() ?>"> <a class="blog__frame" href="<?= the_permalink() ?>">
@@ -73,13 +66,13 @@ $colon_query = new WP_Query(
</a> </a>
<?php get_template_part("template-parts/micro/post"); ?> <?php //get_template_part("template-parts/micro/post"); ?>
<div class="blog__detail"> <div class="blog__detail">
<?php get_template_part("template-parts/post/blog-date"); ?> <?php get_template_part("template-parts/post/blog-date"); ?>
<?php get_template_part("template-parts/post/blog-author"); ?> <?php get_template_part("template-parts/post/colon-author"); ?>
</div> </div>

View File

@@ -1,13 +1,18 @@
<!--[home/index]--> <!--[home/index]-->
<?php get_template_part("template-parts/home/news"); ?> <?php //get_template_part("template-parts/home/news");
cached_get_template_part( 'template-parts/home/news' );?>
<div class="col-12 col-md-8 col-xl-6 float-left"> <div class="col-12 col-md-8 col-xl-6 float-left">
<?php get_template_part("template-parts/home/main-item") ?> <?php //get_template_part("template-parts/home/main-item");
cached_get_template_part( 'template-parts/home/main-item' );
?>
<?php get_template_part("template-parts/home/colon-item") ?> <?php //get_template_part("template-parts/home/colon-item");
cached_get_template_part( 'template-parts/home/colon-item' );
?>
</div> </div>
@@ -22,7 +27,8 @@
</div> </div>
<?php get_template_part("template-parts/home/list-items") ?> <?php //get_template_part("template-parts/home/list-items") ?>
<?php cached_get_template_part( 'template-parts/home/list-items' ); ?>
<?php get_template_part("template-parts/home/ajax-load-more") ?> <?php get_template_part("template-parts/home/ajax-load-more") ?>

View File

@@ -78,6 +78,7 @@
<div class="header__nav__stick stick js-stick-header js-is-sticky sticky-element-is-a-child-of-parent d-none d-md-block"> <div class="header__nav__stick stick js-stick-header js-is-sticky sticky-element-is-a-child-of-parent d-none d-md-block">
<div class="header__nav header__nav--index clearfix"> <div class="header__nav header__nav--index clearfix">
<div class="float-xs-none float-md-left"> <div class="float-xs-none float-md-left">
@@ -102,6 +103,8 @@
</li> </li>
<div class="logo-stick"><a href="https://profile.ru"><img src="https://cdn.profile.ru/wp-content/themes/profile/assets/img/profile-logo-delovoy.svg"></a></div>
<?php get_template_part("template-parts/nav/header-nav-main") ?> <?php get_template_part("template-parts/nav/header-nav-main") ?>
</ul> </ul>

View File

@@ -10,12 +10,10 @@
<?php foreach ( $authors as $author ): ?> <?php foreach ( $authors as $author ): ?>
<a class="article__author" href="<?= get_author_posts_url( $author->ID, $author->user_nicename ); ?>" itemprop="author" itemscope itemtype="https://schema.org/Person"> <a class="article__author" href="<?= get_author_posts_url( $author->ID, $author->user_nicename ); ?>">
<?= $author->display_name; ?> <?= $author->display_name; ?>
<meta itemprop="name" content="<?= htmlspecialchars($author->display_name); ?>" />
<link itemprop="url" href="<?= get_author_posts_url( $author->ID, $author->user_nicename ); ?>" />
</a> </a>

View File

@@ -1,8 +1,10 @@
<!--[single/post-most-popular-item]--> <!--[single/post-most-popular-item]-->
<div class="col-12 col-md-4 d-none" data-id="<?= get_the_ID() ?>"> <?php $post_id = get_the_ID();?>
<a class="partners__item d-flex d-md-block" href="<?= the_permalink() ?>"> <div class="col-12 col-md-4 d-none" data-id="<?php echo $post_id ?>">
<a class="partners__item d-flex d-md-block" href="<?php the_permalink() ?>">
<?php //get_template_part("template-parts/micro/post"); ?> <?php //get_template_part("template-parts/micro/post"); ?>
@@ -10,11 +12,19 @@
<figure> <figure>
<img loading="lazy" <?php if ( has_post_thumbnail($post_id) ): ?>
<img loading="lazy"
itemprop="image" itemprop="image"
class="d-block" class="d-block"
src="<?= the_post_thumbnail_url("thumb-264"); ?>" src="<?= the_post_thumbnail_url("thumb-264"); ?>"
alt="<?= htmlspecialchars( get_the_title() ) ?>" /> alt="<?= htmlspecialchars( get_the_title() ) ?>" />
<?php else:?>
<img loading="lazy"
itemprop="image"
class="d-block"
src="<?= wp_get_attachment_image_url(1357368, 'thumb-264');?>"
alt="<?= htmlspecialchars( get_the_title() ) ?>" />
<?php endif?>
</figure> </figure>