Skip to content

Instantly share code, notes, and snippets.

@Aquei
Last active June 5, 2023 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aquei/5ce92040d43733954f35 to your computer and use it in GitHub Desktop.
Save Aquei/5ce92040d43733954f35 to your computer and use it in GitHub Desktop.
just-add-cache-control
max_age.json
<?php
/*
Plugin Name: Just Add Cache-Control
Plugin URI: https://gist.github.com/Aquei/5ce92040d43733954f35
Description: Http header のCache-Controlを追加するだけ
Author: aquei
Version: 0.1.2
Author URI: http://blog.srytk.com/aquei/
License: Apache License, Version 2.0
*/
class JustAddCacheControl
{
//ページ別max-age
public $max_age = array(
"attachment" => null
,"author" => null
,"category" => null
,"date" => null
,"embed" => null
,"home" => null
,"page" => null
,"tag" => null
,"404" => null
,"feed" => null
,"search" => null
,"font_page" => null
,"single" => null
,"archive" => null
,"singular" => null
);
//cache-controlの値(max-ageを除く)
public $suffix = ', public';
function __construct(){
//ビジターがログイン中ならなにもしない
if(is_user_logged_in()){
return;
}
$config_path = __DIR__ . '/max_age.json';
if (is_file($config_path)) {
$config = json_decode($config_path, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($config)) {
$this->max_age = $config;
}
}
//hookに登録
add_filter('wp_headers', [$this, 'setMaxAge']);
}
function getMaxAge(){
if (isset($_SERVER['HTTP_ACCEPT'])){
$ha = strtolower($_SERVER['HTTP_ACCEPT']);
if (strpos($ha, 'application/ld+json') !== false || strpos($ha, 'application/activity+json') !== false) {
return -1;
}
}
forEach($this->max_age as $ind => $maxAge){
$func_name = "is_".$ind;
if(function_exists($func_name) && $func_name()){
return $maxAge;
}
}
//該当するページが無かった
return false;
}
function setMaxAge($headers){
$age = $this->getMaxAge();
if($age !== false && $age !== null && is_int($age) && $age >= 0){
$headers['Cache-Control'] = "max-age={$age}{$this->suffix}";
}else if($age === -1){
$headers['Cache-Control'] = 'private, must-revalidate, no-cache';
}
return $headers;
}
}
/*
* is_user_logged_in()は後から読み込まれるのでwrapする
*/
function init_jacc(){
$jacc = new JustAddCacheControl();
}
add_action('init', 'init_jacc');
{
"attachment":null,
"author":null,
"category":null,
"date":null,
"embed":null,
"home":null,
"page":null,
"tag":null,
"404":null,
"feed":null,
"search":null,
"font_page":null,
"single":null,
"archive":null,
"singular":null
}
@Aquei
Copy link
Author

Aquei commented Sep 5, 2015

説明

cache-control http headerを付与するwordpress plugin
ログインユーザには何もしない

使い方

ページのタイプ別にブラウザキャッシュ時間(max-age)をnullから秒数に変更する。例えばsingleをnullから60*60*24*3にして3日キャッシュさせるとか。
wp-content/pluginsjust-add-cache-controlというディレクトリを作って、変更したjust-add-cache-control.phpをコピーする
後は管理画面からjust-add-cache-controlを有効にするだけ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment