2011-02-24 21 views
0

什麼是最有效的方式(按時間)來計算從查詢返回的帖子數量並解析返回的帖子?

第1部分:

我現在有這樣的代碼:

/* $query = { 
'numberposts' = '15', 
'queryvar1' = '…', 
'queryvar2' = '…'; 
} 
*/ 
$lastposts = get_posts($query); // This uses the original query, and will only return 15 results 

$print['returnedcount'] = count($lastposts); // Uses some resources (+ acceptable time) 

$query['numberposts'] = "-1"; // Get total results from query 
$print['totalposts'] = count(get_posts($query)); // Uses lots of resources (+ lots of time) 

我有沒有用這個第二get_posts($query) - 提供我與其他數據,我怎麼能速度呢?我只需要統計由查詢(返回除了numberposts - 值帖子總數

第2部分:

-object稍後將用來獲得post數據(ID,日期的$lastposts ,標題,評論數,縮略圖和作者ID)

這些的數據都是inputed到$print - 陣列是這樣的:

foreach ($lastposts as $post){ 
    // ID 
    $print['id'][] = (string)$post->ID; 
    // Date 
    $print['date'][] = (string)$post->post_date; 
    // Title 
    $print['title'][] = (string)$post->post_title; 
    // Comment count 
    $print['comments'][] = (string)$post->comment_count; 
    // Images 
    $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium'); 
    $print['image'][] = (string)$image[0]; 
    $imageRetina = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large'); 
    $print['imageretina'][] = (string)$imageRetina[0]; 
    // Author 
    $print['author'][] = (string)$post->post_author; 
} 

有沒有更時間有效的方式來做到這一點?我注意到,圖像操作確實需要一段時間。

非常感謝!

回答

2

對於第一部分,您可以創建一個新的WP_Query對象,而不是使用get_posts。這應該比您的問題中的代碼更有效,但差異可能可以忽略不計。

$query = new WP_Query(); 
$query->query(array(
    'posts_per_page' => 15 
)); 

$print['returnedcount'] = $query->post_count; 
$print['totalposts'] = $query->found_posts; 
+0

謝謝,我會嘗試(: – Emil 2011-02-24 21:46:03

+0

這是我最終做的。非常感謝!:) – Emil 2011-03-31 16:59:40

-1

你能填充你所需要的第一次查詢運行的陣列 - 這將使運行get_posts()不必要的。

所以,在你的模板文件,你有

while(have_posts()): the_post(); 
    // do your normal output here e.g. the_content(); etc. 

    $print['title'][] = get_the_title(); 
    // any more data you want to collect. 

endwhile; 

你可以移動整個數據收集位的functions.php。你也在使用緩存嗎?這可能有幫助。 (例如http://wordpress.org/extend/plugins/hyper-cache/

+0

我正在開發一個插件,通過AJAX請求運行,所以使用循環是不是一個選項,不幸的是:) – Emil 2011-02-24 21:45:08

+0

你可以使用會話變量來存儲在循環過程中獲得的信息,然後在ajax請求進來時使用該信息? – JasonC 2011-02-24 21:49:56