关于WP数据库优化,看看这2段代码 哪段是对的? [ol]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);[/ol]复制代码 代码, 数据库
和这个对比 [ol]//优化数据库慢查询if ( ! function_exists( 'banzhuti_set_no_found_rows' ) ) : /** * 设置WP_Query的 'no_found_rows' 属性为true,禁用SQL_CALC_FOUND_ROWS * 更多优化教程-搬主题www.banzhuti.com * @param WP_Query $wp_query The WP_Query instance. * @return void */ function banzhuti_set_no_found_rows( \WP_Query $wp_query ) { $wp_query->set( 'no_found_rows', true ); }endif;add_filter( 'pre_get_posts', 'banzhuti_set_no_found_rows', 10, 1 ); if ( ! function_exists( 'banzhuti_set_found_posts' ) ) : /** * Workout the pagination values. * * 为这个wp_query构建和设置分页结果 * */ function banzhuti_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' ] : ''; // 构建并运行查询。将结果设为'found_posts' // 在我们要运行的主要查询上设置参数. $wp_query->found_posts = $wpdb->get_var( "SELECT $distinct COUNT(*) FROM {$wpdb->posts} $join WHERE 1=1 $where" ); // 计算出每页应该有多少文章 $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' ) ) ); // 设置max_num_pages(最大页数). $wp_query->max_num_pages = ceil( $wp_query->found_posts / $posts_per_page ); // Return the $clauses so the main query can run. return $clauses; }endif;add_filter( 'posts_clauses', 'banzhuti_set_found_posts', 10, 2 );[/ol]复制代码