<?php
/*
Plugin Name: Shortcode output be cached
Plugin URI:
Description: Shortcode output be cached. [be_cache _name="target shortcode name" _id="cache id" _keyword="success keyword" atts...]
*/
namespace be_cache_shortcode;
function be_cache($atts, $content = null, $tag) {
global $shortcode_tags;
if (!array_key_exists('_name', $atts)) {
return '<p>be_cache: _name is not defined.</p>';
}
if (!array_key_exists('_id', $atts)) {
return '<p>be_cache: _id is not defined.</p>';
}
$tag = $atts['_name']; // shortcode name
$gid = $atts['_id']; // cache id
$keyword = '';
if (array_key_exists('_keyword', $atts)) {
$keyword = $atts['_keyword'];
}
if (!array_key_exists($tag, $shortcode_tags)) {
return '<p>be_cache: _name: "'.$tag.'" is not found.</p>';
}
$results = '';
$error = '';
if (!check_cache($gid)) {
// echo '<p>get shortcode data</p>';
$results = $shortcode_tags[$tag]($atts, $content, $tag);
if ($keyword) {
if (stripos($results, $keyword) !== FALSE) {
// echo '<p>success get shortcode data</p>';
save_cache($gid, $results);
} else {
$error = ' <!-- be_cache: output is error: '.$results.' -->';
$results = '';
}
} else if ($results) {
// echo '<p>success get shortcode data</p>';
save_cache($gid, $results);
}
}
if (!$results) {
// echo '<p>load cache data</p>';
$results = load_cache($gid, $results);
}
return $results.$error;
}
function cache_path($gid) {
$dir = wp_upload_dir(null, false, false);
// print_r($dir);
return $dir['basedir'].'/shortcode-be-cache-'.$gid.'.cache'; // uploads/rss-feed-url...\.cache
}
function check_cache($gid) {
$path = cache_path($gid);
if (!file_exists($path)) {
return false;
}
if (date("Ymd", filemtime($path)) < date("Ymd", time())) {
return false;
}
return true;
}
function save_cache($gid, $data) {
return file_put_contents(cache_path($gid), $data);
}
function load_cache($gid) {
return file_get_contents(cache_path($gid));
}
if (!shortcode_exists('be_cache')) {
add_shortcode('be_cache', 'be_cache_shortcode\be_cache');
}