WordPress优化之缓存侧边栏

之前有写关于wordpress优化的文章:

使用下来,Opcache+Memcached+WP Rocket组合效果非常好,但是无意间发现,原来这整个组合,也没有让wordpress侧边栏被缓存,也就是说,wordpress侧边栏是动态查询的,尤其是如果侧边栏有相关推荐,等动态内容的时候,每次打开页面wordpress都会动态查询数据库,即使用了 Opcache+Memcached+WP Rocket ,也不会缓存侧边栏。

update:关闭WP Rocket预缓存,就可以缓存侧边栏,原文连接在文章结尾;

同时,下面的方法对于开启wordpress多站点的,会有问题,可能会出现因跨域加载而页面混乱。

网上找到我爱水煮鱼关于缓存侧边栏的文章,试验下效果不错。但是他的代码有几个语法错误,保存后会报错,网上其他人抄代码的,竟然都没有指出错误,错误代码一起抄!!

我已经修改过来了。

  1. 进入 WordPress 后台,点击外观 => 主题编辑 => Sidebar (sidebar.php)。
  2. 在 sidebar.php 开头加入以下代码:
<?php 
$sidebar_html = ABSPATH . "wp-content/cache/sidebar.txt";
$have_cached = false;
if (file_exists($sidebar_html)){
    $file_time = filemtime($sidebar_html);
    if (($file_time + 3600) > time()){ //缓存1小时
        echo "<!-- cached sidebar -->";
        echo(file_get_contents($sidebar_html));
        echo "<!-- end of cached sidebar -->";
        $have_cached = true;
    }
}
if(!$have_cached){
    ob_start();}
?>

在 sidebar.php 结尾加入以下代码:

<?php
    $sidebar_content = ob_get_contents();
    ob_end_clean();
    $sidebar_fp = fopen($sidebar_html, "w");
 
    if ($sidebar_fp){
         fwrite($sidebar_fp, $sidebar_content);
         fclose($sidebar_fp);
    }
 
    echo $sidebar_content;
?>

我爱水煮鱼原文连接:https://blog.wpjam.com/m/cache-sidebar/

关闭侧边栏文章连接:https://cloud.tencent.com/developer/article/1072002

本文链接: https://www.168itw.com/wordpress/wordpress-sidebar-cached/
转载请注明转载自:168itw

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注