WordPress网站文章非常多时,解决数据库查询使网站非常慢的问题

WordPress的文章数量超过10万会明显感觉网站查询效率下降

WordPress在查询post时,默认会同时把文章数量也查询出来
当post数量到10w+时,query_posts和WP_Query会因为SQL_CALC_FOUND_ROWS出现慢查询
慢查询SQL语句为

1
2
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' ) ORDER BY wp_posts.post_date DESC LIMIT 0, 20
SELECT FOUND_ROWS()

解决办法:
方法一、彻底禁用SQL_CALC_FOUND_ROWS

1
2
3
4
5
6
7
8
9
add_action('pre_get_posts', 'wndt_post_filter');
function wndt_post_filter($query) {
    if (is_admin() or !$query->is_main_query()) {
        return $query;
    }

    // 禁止查询 SQL_CALC_FOUND_ROWS
    $query->set('no_found_rows', true);
}

方法二、如果仍然需要查询文章数量,使用更加高效的EXPLAIN方式代替SQL_CALC_FOUND_ROWS

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
if ( ! function_exists( 'maizi_set_no_found_rows' ) ) {
    /**
     * 设置WP_Query的 'no_found_rows' 属性为true,禁用SQL_CALC_FOUND_ROWS
     *
     * @param  WP_Query $wp_query WP_Query实例
     * @return void
     */
    function maizi_set_no_found_rows(\WP_Query $wp_query)
    {
        $wp_query->set('no_found_rows', true);
    }
}
add_filter( 'pre_get_posts', 'maizi_set_no_found_rows', 10, 1 );


if ( ! function_exists( 'maizi_set_found_posts' ) ) {
    /**
     * 使用 EXPLAIN 方式重构
     */
    function maizi_set_found_posts($clauses, \WP_Query $wp_query)
    {
        // Don't proceed if it's a singular page.
        if ($wp_query->is_singular()) {
            return $clauses;
        }

        global $wpdb;

        $where = isset($clauses['where']) ? $clauses['where'] : '';
        $join = isset($clauses['join']) ? $clauses['join'] : '';
        $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : '';

        $wp_query->found_posts = (int)$wpdb->get_row("EXPLAIN SELECT $distinct * FROM {$wpdb->posts} $join WHERE 1=1 $where")->rows;

        $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')));

        $wp_query->max_num_pages = ceil($wp_query->found_posts / $posts_per_page);

        return $clauses;
    }
}
add_filter( 'posts_clauses', 'maizi_set_found_posts', 10, 2 );
原文链接:https://xiaohost.com/3621.html,转载请注明出处。
0

评论0

请先