I started making the following caching codes in order to create an experimental plugin that provides a solution to my own needs.
add_action('wp_loaded', 'buffer_start');
add_action('shutdown', 'buffer_end');
add_action('wp', 'cache_control');
function cache_control()
{
if (!is_admin() && !(defined('DOING_AJAX') && DOING_AJAX)) {
$cache = get_transient('cache');
if(!empty($cache) || $cache != '') {
die($cache);
}
}
}
function buffer_start()
{
ob_start("callback");
}
function buffer_end()
{
ob_get_clean();
}
function callback($html)
{
if (!is_admin() && !(defined('DOING_AJAX') && DOING_AJAX)) {
$cache = get_transient('cache');
if(empty($cache) || $cache == '') {
set_transient('cache', $html);
}
}
return $html;
}
Leaving aside the many shortcomings in the scenario and the fact that the first cache will appear on all pages, I have a few questions.
- idea – First of all, if there is
HTML
in the cache, WordPress functions should work as little as possible and respond to the server response as soon as possible. - question – In this case, are the
hooks
I used in my coding correct?
What I’m saying is, is there a hook that kicks in earlier to check for cache availability with the
add_action('wp'
hook, and if so, prevent WordPress from wasting more time? Or is that correct?
- idea – If a cache is found, WordPress needs to respond in the most appropriate and fast way possible and skip the time it takes to produce an HTML result.
- Question – You may have noticed that I used the PHP
die()
feature to do this. In practice this doesn’t make much sense to me, but I should get out of there as soon as possible and not follow WordPress’ classic functions to return a “200 Response”. Is there a more convenient way or a WordPress feature to do this? Or is the way I’m doing the best?
Of course, apart from all these, “Lite Speed Cache” etc. I know many plugins do all of this completely and intelligently. My goal is primarily to push the limits, create my own infrastructure, and of course write a special plugin that offers specific solutions to my needs. For this reason, I wanted to tinker with the plugins I mentioned to get help, but they have a very complex and difficult infrastructure to reverse engineer.
So, generally is the path I followed correct or if there are alternative and better solutions at the beginning, I want to move forward by completing them for these few important features because I know that as I start to go into details, things will start to get a little more complicated 🙂