問題描述

每次在下面的函數中調用 WP_Query() 時,Wordpress 會泄漏 8 兆的內存。而且,由於我調用這個函數很多東西很快就會變得很漂亮 (:(我已經嘗試取消設置結果 $ queryObject 以及週期性地調用 wp_cache_flush(),但是似乎沒有任何效果。

function get_post_ids_in_taxonomies($taxonomies, &$terms=array()) {
    $post_ids = array();

    $query = gen_query_get_posts_in_taxonomies($taxonomies, $terms);
    // var_dump($query);

    //Perform the query
    $queryObject = new WP_Query($query); //*****THE 8 MEGABYTES IS LEAKED HERE*****

    //For all posts found...
    if($queryObject->have_posts()) {
        while($queryObject->have_posts()) {
            $queryObject->the_post();

            //Get the $post_id by capturing the output of the_ID()
            ob_start();
            the_ID();
            $post_id = (int) ob_get_contents();
            ob_end_clean();

            // echo $post_id."n";
            $post_ids[] = $post_id;
        }
    }

    unset($queryObject);

    return $post_ids;
}

gen_query_get_posts_in_taxonomies() 是:

function gen_query_get_posts_in_taxonomies($taxonomies, &$terms=array()) {
    //General query params
    $query = array(
        'posts_per_page'    => -1,  //Get all posts (no paging)
        'tax_query'             => array('relation' => 'OR'),
    );

    //Add the specific taxonomies and terms onto $query['tax_query']
    foreach($taxonomies as $tax) {
        //Get terms in the taxonomies if we haven't yet
        if(!array_key_exists($tax, $terms)) {
            $terms[$tax] = array();

            $terms_tmp = get_terms($tax);
            foreach($terms_tmp as $tt)
                $terms[$tax][] = $tt->term_taxonomy_id;
        }

        $query['tax_query'][] = array(
            'taxonomy' => $tax,
            'terms' => $terms[$tax],
            'field' => 'term_taxonomy_id',
        );
    }

    return $query;
}

最佳解決方案

對 WP 黑客很有反應:http://lists.automattic.com/pipermail/wp-hackers/2012-June/043213.html

What you’re doing with that query, is loading EVERY matching post into memory, including the full post contents. As you can imagine, this is probably quite a lot of items.

You can pass ‘fields’ => ‘ids’ into WP_Query to simply return a list of matching post_ids instead, which should reduce the memory (and processing time) significantly:

http://codex.wordpress.org/Class_Reference/WP_Query#Post_Field_Parameters

次佳解決方案

在研究這個 memory 問題的同時,絆倒了這裏。

在這種情況下,您可以使用 get_the_id 而不是使用緩衝來捕獲 ID,並且可以將查詢的字段縮小為僅包含 ids 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。