functions.php禁用SQL_CALC_FOUND_ROWS

admin 2022年8月31日23:03:54WordPress技巧评论1,922 次浏览阅读模式

functions.php

 

 

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 2=2 $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 );

相关文章
weinxin
我的微信
微信扫一扫
admin
  • 本文由 发表于 2022年8月31日23:03:54
  • 转载请务必保留本文链接:https://anyun.org/a/webtips/wordpressjiqiao/2022/0831/12386.html

发表评论

匿名网友 填写信息

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