WordPress提交评论的时删除该页面的缓存

2024年10月18日15:45:44 2
微信搜一搜 ts小陈

今天无意间发现评论换个浏览器就看不见一想就是缓存的问题,但是我使用的是《WordPress安装memcached提升网站速度》没有设置项无法将评论排除在外。

方法一

WordPress提交评论的时删除该页面的缓存

编辑主题下的 comments-ajax.php 文件(启用 ajax 评论的博客才有),找到如下代码:

do_action('pre_comment_on_post', $comment_post_ID);

然后,在这行代码之后添加删除缓存代码,保存即可:

  1. //有人评论将自动删除已存在缓存
  2. $post_data = get_post($post->ID, ARRAY_A);
  3. $slug = $post_data['post_name'];
  4. $cache_s = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$post->ID.".html/index.html";
  5. $cache_sd = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$post->ID.".html";
  6. $cache_p = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$slug."/index.html";
  7. $cache_pd = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$slug;
  8. if (file_exists($cache_s)) {
  9.     if (unlink($cache_s) === false) {
  10.         error_log("Failed to delete cache file: $cache_s");
  11.     }
  12.     if (rmdir($cache_sd) === false) {
  13.         error_log("Failed to remove directory: $cache_sd");
  14.     }
  15. }

方法二

将以下代码添加到主题functions.php文件中

WordPress提交评论的时删除该页面的缓存

  1. add_action('wp_insert_comment', function($comment_id) {
  2.     $comment = get_comment($comment_id);
  3.     $post_id = $comment->comment_post_ID;
  4.     // 清理与文章相关的缓存
  5.     $slug = get_post_field('post_name', $post_id);
  6.     $cache_s = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$post_id.".html/index.html";
  7.     $cache_sd = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$post_id.".html";
  8.     $cache_p = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$slug."/index.html";
  9.     $cache_pd = WP_CONTENT_DIR."/cache/supercache/".$_SERVER['SERVER_NAME']."/".$slug;
  10.     if (file_exists($cache_s)) {
  11.     unlink($cache_s);
  12.     rmdir($cache_sd);
  13. }
  14. if (file_exists($cache_p)) {
  15.     unlink($cache_p);
  16.     rmdir($cache_pd);
  17. }
  18. }, 10, 1);
小陈号卡
ts小陈

发表评论(不允许含有网址!)

:?: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :cry: :mrgreen: :neutral: :razz:

已登录用户不需要填写以下内容

目前评论:2   其中:访客  0   博主  0

    • avatar 老白博客  美国 0

      发不了任何评论,你这