What's the most effective way (time-smart) to count quantity of posts came back from the query and parse the posts came back?


I presently have this code:

/* $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)

I've no use for that other data this second get_posts($query)-generates for me, how do i speed that up? I only have to count the entire quantity of posts came back through the query (except the numberposts-value.


The $lastposts-object is going to be used later to obtain publish data (ID, date, title, comment count, thumbnail and author ID).

These datas are inputed in to the $print-array such as this:

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;

It is possible to additional time-efficient method of doing this? I've observed the image-actions do take quite a while.

Thanks alot!

For the beginning you can produce a new WP_Query object instead of using get_posts. This ought to be more effective compared to code inside your question, however the difference will probably be minimal.

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

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

Would you populate an assortment with the thing you need the very first time the totally run - that will make running get_posts() unnecessary.

So, inside your template files you've

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.


You can slowly move the whole data collection bit to functions.php. Are you currently using caching too? That can help. (e.g. http://wordpress.org/extend/plugins/hyper-cache/)