wordpress文章数量超过10万时,打开速度慢怎么解决?-kb88凯时官网登录

时间:2022-02-23
阅读:
免费资源网 - https://freexyz.cn/

当网站的文章数量超过10万篇时,明显感觉到打开速度变慢了很多。

变慢的原因

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()

query_posts和wp_query会因为sql_calc_found_rows出现慢查询。

解决办法一:彻底禁用sql_calc_found_rows

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方式

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://freexyz.cn/
返回顶部
顶部
网站地图