1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<?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'); } |