Files
profile/block-cache-manager.php

113 lines
3.3 KiB
PHP
Raw Normal View History

2025-08-27 00:00:02 +03:00
<?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);
?>