Files
profile/block-cache-manager.php
2026-01-12 13:37:40 +03:00

132 lines
4.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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);
}
}
// Функция очистки главной страницы
function clear_index_cache () {
$index_file = '/var/www/profile/html/wp-content/uploads/fpcache/regenerate/index.html';
if (file_exists($index_file)) {
return unlink($index_file);
}
return false;
}
/**
* Общая функция для сброса кеша на основе условий поста
*
* @param WP_Post $post Объект поста (уже содержит ID)
*/
function clear_post_cache_based_on_conditions( $post_id, $post ) {
$fpc_signal = WP_CONTENT_DIR . '/uploads/fpcache/.last_modified';
// Обновляем сигнальный файл если вдруг прервется выполнение
touch($fpc_signal);
// Кеш по типу поста
if ($post->post_type == 'profile_article') {
clear_template_cache('template-parts/home/main-item');
clear_template_cache('template-parts/home/colon-item');
clear_template_cache('template-parts/home/list-items'); //всегда в конце тк могут переместиться из предыдущих
} 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');
clear_template_cache('template-parts/home/list-items');
clear_index_cache(); // на всякий случай сбросим главную
}
// Сброс колонки
$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');
clear_template_cache('template-parts/home/list-items');
clear_index_cache(); // на всякий случай сбросим главную
}
// Обновляем сигнальный файл по завершению
touch($fpc_signal);
}
// Хук для обычного сохранения
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;
clear_post_cache_based_on_conditions($post->ID, $post); // Передаем только $post
}, 10, 3);