0

我正在寻找有关 Wordpress 的旧主题的后续内容,当您在 Wordpress 中拥有大型数据库时,发现 SQL_CALC 会减慢速度。我一直在使用这篇文章底部的代码来解决它,但它确实在我的错误日志中生成了一个错误。我将如何防止此错误?

 PHP Warning:  Division by zero in /var/www/vhosts/domain.com/httpdocs/wp-content/themes/greatTheme/functions.php on line 19

原帖: http ://wordpress.org/support/topic/slow-queries-sql_calc_found_rows-bringing-down-site?replies=25

我的functions.php中的代码:

 add_filter('pre_get_posts', 'optimized_get_posts', 100);
 function optimized_get_posts() {
    global $wp_query, $wpdb;

    $wp_query->query_vars['no_found_rows'] = 1;
    $wp_query->found_posts = $wpdb->get_var( "SELECT COUNT(*) FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')" );
    $wp_query->found_posts = apply_filters_ref_array( 'found_posts', array( $wp_query->found_posts, &$wp_query ) );
    $wp_query->max_num_pages = ceil($wp_query->found_posts / $wp_query->query_vars['posts_per_page']);

    return $wp_query;
 }
4

2 回答 2

1

大概$wp_query->query_vars['posts_per_page']设置为 0,这意味着您要求 PHP 除以$wp_query->found_posts零。当然,这是做不到的。我不知道在你的代码中哪里设置了这个变量(WP 处理这个吗?)但很容易通过print_r $wp_query->query_vars['posts_per_page'];在该行之前添加一个来确认这一点。

于 2012-04-10T06:58:31.467 回答
1

根据@Daan 的建议,我尝试了以下方法,但没有产生任何错误:

add_filter('pre_get_posts', 'optimized_get_posts', 100);
function optimized_get_posts() {
    global $wp_query, $wpdb;
    $wp_query->query_vars['no_found_rows'] = 1;
    $wp_query->found_posts = $wpdb->get_var( "SELECT COUNT(*) FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')" );
    $wp_query->found_posts = apply_filters_ref_array( 'found_posts', array( $wp_query->found_posts, &$wp_query ) );
    if($wp_query->query_vars['posts_per_page'] <= 0) {
        $wp_query->max_num_pages = 0;
    } else {
        $wp_query->max_num_pages = ceil($wp_query->found_posts / $wp_query->query_vars['posts_per_page']);
    }
    return $wp_query;
}

基本上,代码检查是否$wp_query->query_vars['posts_per_page']有一个正值,因此能够$wp_query->found_posts适当地划分。

于 2012-04-16T21:39:24.390 回答