WordPress教程

WordPress文章过多导致跳转文章时加载过慢的问题优化

阿里云

根据我们长期开发的经验,大多数 WordPress 网站都有数百到数千篇文章。此时,普通用户不会对网站的打开速度感到任何异常。但是如果 WordPress 网站的文章数量超过 10 万,即使网站服务器的配置很强大,网站的打开速度基本上也会很慢。

这是因为 WordPress 在查询文章列表时,默认也会查询文章数。这对于少量的网站数据应该不会造成任何问题,但是对于大量的文章是不可避免的。慢查询。主机引用的一位用户告诉我们,他的网站有 40 万篇文章,打开首页需要一两分钟,甚至首页或文章页也经常打不开。

也想出现在这里?联系我们
创客主机

WordPress 网站查询慢的原因:WordPress 在查询帖子列表时,默认也会查询帖子数。使用此方法:get_posts、query_posts 和 WP_Query。get_posts 在 4.6.1+中没有使用 SQL_CALC_FOUND_ROWS,但是 query_posts 和 WP_Query 仍然使用,所以需要优化

1、完全禁用 SQL_CALC_FOUND_ROWS,放到 functions.php 文件中

  1. add_action('pre_get_posts', 'wndt_post_filter');
  2. function wndt_post_filter($query) {
  3.     if (is_admin() or !$query->is_main_query()) {
  4.         return $query;
  5.     }
  6.  
  7.     // 禁止查询 SQL_CALC_FOUND_ROWS
  8.     $query->set('no_found_rows', true);
  9. }

2、如果您还需要查询文章数,请使用更高效的 EXPLAIN 方法代替 SQL_CALC_FOUND_ROWS,以更高效的方式禁用 SQL_CALC_FOUND_ROWS。这里我们使用 EXPLAIN 方法。具体代码如下,放在 functions.php 文件中

  1. if ( ! function_exists( 'zjck_set_no_found_rows' ) ) {
  2.     /**
  3.      * 设置WP_Query的 'no_found_rows' 属性为true,禁用SQL_CALC_FOUND_ROWS
  4.      *
  5.      * @param  WP_Query $wp_query WP_Query实例
  6.      * @return void
  7.      */
  8.     function zjck_set_no_found_rows(\WP_Query $wp_query)
  9.     {
  10.         $wp_query->set('no_found_rows', true);
  11.     }
  12. }
  13. add_filter( 'pre_get_posts', 'zjck_set_no_found_rows', 10, 1 );
  14.  
  15.  
  16. if ( ! function_exists( 'zjck_set_found_posts' ) ) {
  17.     /**
  18.      * 使用 EXPLAIN 方式重构
  19.      */
  20.     function zjck_set_found_posts($clauses, \WP_Query $wp_query)
  21.     {
  22.         // Don't proceed if it's a singular page.
  23.         if ($wp_query->is_singular()) {
  24.             return $clauses;
  25.         }
  26.  
  27.         global $wpdb;
  28.  
  29.         $where = isset($clauses['where']) ? $clauses['where'] : '';
  30.         $join = isset($clauses['join']) ? $clauses['join'] : '';
  31.         $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : '';
  32.  
  33.         $wp_query->found_posts = (int)$wpdb->get_row("EXPLAIN SELECT $distinct * FROM {$wpdb->posts} $join WHERE 1=1 $where")->rows;
  34.  
  35.         $posts_per_page = (!empty($wp_query->query_vars['posts_per_page']) ? absint($wp_query->query_vars['posts_per_page']) : absint(get_option('posts_per_page')));
  36.  
  37.         $wp_query->max_num_pages = ceil($wp_query->found_posts / $posts_per_page);
  38.  
  39.         return $clauses;
  40.     }
  41. }
  42. add_filter( 'posts_clauses', 'zjck_set_found_posts', 10, 2 );

WordPress 文章过多导致跳转文章时加载过慢的问题优化

已有 153 人购买
查看演示升级 VIP立刻购买

收藏
(1)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!