Make WP_Query more efficient?

时间:2013-02-13 作者:v3nt

Ok-所以使用WP\\u查询来计算用户的投票数。但现在有23000张选票,占用了大量内存。

有什么方法可以提高此WP\\U查询的效率吗?

$args = array(
    \'post_type\' => \'vote\',
    \'author\'=>$user,
    \'meta_key\'=>\'comp_question\',
    \'meta_value\'=>$question_id,
    \'meta_compare\'=>\'=\',
    \'orderby\'=>\'date\',
    \'order\'=>\'desc\'
);

$the_query = new WP_Query( $args );
感谢您的帮助!感谢您的帮助!

1 个回复
SO网友:birgire

您可以尝试以下一些额外参数:

 \'update_post_term_cache\' => false,
 \'update_post_meta_cache\' => false, 
 \'cache_results\'=>false,
 \'no_found_rows\' => true, 
 \'posts_per_page\'=>1,
 \'post_status\'=\'publish\',
ps:您可以在使用测试时测量查询的速度microtime()

http://php.net/manual/en/function.microtime.php

Edit:

还有一种方法:

function count_votes($user_id=1, $question_id=1, $post_type=\'vote\', $meta_key=\'comp_question\'){
    global $wpdb;

    $sql = "SELECT count(*) FROM {$wpdb->posts} INNER JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) WHERE ({$wpdb->posts}.post_author = %d) AND ({$wpdb->posts}.post_type = %s) AND ({$wpdb->posts}.post_status = \'publish\' ) AND ({$wpdb->postmeta}.meta_key = %s) AND ({$wpdb->postmeta}.meta_value = %d)"; 

    // uncomment if you need to group it
    //$sql .= "  GROUP BY {$wpdb->posts}.ID"; 

    $count = $wpdb->get_var($wpdb->prepare($sql,$user_id,$post_type,$meta_key,$question_id));

    return $count;
}
您可以这样使用它:

$user_id=1;
$question_id=1; 
$post_type=\'vote\'; 
$meta_key=\'comp_question\';

echo "votes: " . count_votes($user_id, $question_id, $post_type, $meta_key);

Edit 2:

下面是一个返回投票ID数组的函数:

function get_votes($user_id=1, $question_id=1, $post_type=\'vote\', $meta_key=\'comp_question\'){
    global $wpdb;

    $sql = "SELECT {$wpdb->posts}.ID FROM {$wpdb->posts} INNER JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) WHERE ({$wpdb->posts}.post_author = %d) AND ({$wpdb->posts}.post_type = %s) AND ({$wpdb->posts}.post_status = \'publish\' ) AND ({$wpdb->postmeta}.meta_key = %s) AND ({$wpdb->postmeta}.meta_value = %d)"; 

    // uncomment if you need to group it
    //$sql .= "  GROUP BY {$wpdb->posts}.ID"; 

    $ids=array();
    $ids = $wpdb->get_col($wpdb->prepare($sql,$user_id,$post_type,$meta_key,$question_id));

    return $ids;
}
您可以这样使用它:

$ids=get_votes($user_id, $question_id, $post_type, $meta_key);
print_r($ids);

结束