Dipublikasikan: 6 Desember 2025
Terakhir diperbarui: 6 Desember 2025
Dipublikasikan: 6 Desember 2025
Terakhir diperbarui: 6 Desember 2025
Raymond Kelvin Nando — Kode ini saya buat untuk membuat cache halaman statis untuk pengunjung yang tidak login, sehingga website lebih cepat dan lebih ringan. Kodenya menghindari konflik dengan admin, AJAX, REST API, query pencarian, dan URL dinamis.
Daftar Isi
Anda bisa menempelkan kode dibawah ini melalui plugins WPCodePro.
<?php
add_action('init', function() {
if (is_user_logged_in()) return;
if (is_admin()) return;
if (defined('REST_REQUEST') && REST_REQUEST) return;
if (defined('DOING_AJAX') && DOING_AJAX) return;
if ($_SERVER['REQUEST_METHOD'] !== 'GET') return;
if (is_search() || is_feed() || is_preview()) return;
$request_uri = $_SERVER['REQUEST_URI'];
$exclude_paths = [
'/wp-admin', '/wp-login', '/account', '/checkout', '/cart', '/feed'
];
foreach ($exclude_paths as $p) {
if (strpos($request_uri, $p) === 0) return;
}
$query = $_SERVER['QUERY_STRING'] ?? '';
$exclude_q = ['s', 'preview'];
parse_str($query, $params);
foreach ($exclude_q as $q) {
if (isset($params[$q])) return;
}
if (!empty($params)) {
foreach ($params as $k => $v) {
if (preg_match('/^(utm_|gclid|fbclid)/i', $k)) unset($params[$k]);
}
}
$clean_query = empty($params) ? '' : '?' . http_build_query($params);
$url = home_url(parse_url($request_uri, PHP_URL_PATH) . $clean_query);
$cache_dir = WP_CONTENT_DIR . '/cache/wpcodepro-safe/';
if (!is_dir($cache_dir)) wp_mkdir_p($cache_dir);
$ttl = 20 * 60;
$key = md5($url);
$file = $cache_dir . $key . '.html';
if (file_exists($file) && (time() - filemtime($file)) < $ttl) {
$content = file_get_contents($file);
$etag = md5($content);
header('Cache-Control: public, max-age=0, must-revalidate');
header('ETag: "' . $etag . '"');
header('X-WPCodePro-Cache: HIT');
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) === '"' . $etag . '"') {
header("HTTP/1.1 304 Not Modified");
exit;
}
echo $content;
exit;
}
foreach (glob($cache_dir . '*.html') as $old) {
if ((time() - filemtime($old)) > $ttl) unlink($old);
}
ob_start(function($buffer) use ($file) {
file_put_contents($file, $buffer);
return $buffer;
});
});
add_action('save_post', function() {
$cache_dir = WP_CONTENT_DIR . '/cache/wpcodepro-safe/';
if (is_dir($cache_dir)) foreach (glob($cache_dir . '*.html') as $f) unlink($f);
});
Sekian dan Terima Kasih, Semoga Bermanfaat.