function get_cached_post_content($post_id){// 缓存文件路径(建议放在 wp-content/cache 目录,需确保权限)$cache_dir = WP_CONTENT_DIR . '/cache/posts/';$cache_file = $cache_dir . 'post-' . $post_id . '.html';$cache_expire = 3600; // 缓存有效期(秒)// 检查缓存目录是否存在,不存在则创建if (!file_exists($cache_dir)) {wp_mkdir_p($cache_dir);}// 检查缓存文件是否存在且未过期if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_expire)) {// 读取缓存内容return file_get_contents($cache_file);} else {// 缓存过期或不存在,从数据库获取 post 内容$post = get_post($post_id);if (!$post) return '';$content = apply_filters('the_content', $post->post_content); // 应用内容过滤(如短代码解析)// 写入缓存文件file_put_contents($cache_file, $content);return $content;}}// 在主题模板中调用(如 single.php)if (have_posts()) {while (have_posts()) {the_post();echo get_cached_post_content(get_the_ID()); // 输出缓存的内容}}
当 post 被编辑或发布时,需要删除旧缓存,确保内容最新。可添加钩子:
// 当 post 保存或发布时,删除对应缓存function clear_post_cache_on_update($post_id) {$cache_dir = WP_CONTENT_DIR . '/cache/posts/';$cache_file = $cache_dir . 'post-' . $post_id . '.html';if (file_exists($cache_file)) {unlink($cache_file);}}add_action('save_post', 'clear_post_cache_on_update'); // 保存 post 时触发add_action('publish_post', 'clear_post_cache_on_update'); // 发布 post 时触发

