Wordpress SQL_CALC修复导致PHP错误

时间:2012-04-10 05:25:26

标签: php mysql wordpress

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

 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;
 }

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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