WordPress 10w+数据时, 解决SQL_CALC_FOUND_ROWS查询搜索使网站变慢问题

一般来讲WordPress的文章数量达到一定量级时,运行速度就会变慢。网上看到的代码,记录一下解决SQL_CALC_FOUND_ROWS查询使网站变慢问题。

<?php 
/**
 * Plugin Name:  WP Fast Query
 * Plugin URI:   https://www.zhutibaba.com/
 * Description:  WordPress 10w+数据时, 解决SQL_CALC_FOUND_ROWS查询使网站变慢问题
 * Version:      1.0.0
 * Author:       zhutibaba
 * Author URI:   http://www.zhutibaba.com/
 * Author Email: team@zhutibaba.com
 * Text Domain:  wp-fast-query
 * Domain Path:  /languages
 * License:      GPL 2.0
 * License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 */

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


if ( ! function_exists( 'ztbb_set_found_posts' ) ) {
    /**
     * 使用 EXPLAIN 方式重构
     */
    function ztbb_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', 'ztbb_set_found_posts', 10, 2 );

腾讯云限时秒杀【点击购买】

搬瓦工,CN2高速线路,1GB带宽,电信联通优化KVM,延迟低,速度快,建站稳定,搬瓦工BandwagonHost VPS优惠码BWH26FXH3HIQ,支持<支付宝> 【点击购买】!

Vultr$3.5日本节点,512M内存/500G流量/1G带宽,电信联通优化,延迟低,速度快【点击购买】!

阿里云香港、新加坡VPS/1核/1G/25G SSD/1T流量/30M带宽/年付¥288【点击购买】


`微信`扫码 加好友,入群
WordPress插件主题开发定制
Linux服务器配置迁移
扣扣群 665443669

发表评论

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