More efficient Wordpress-query parsing? (get_posts($query))
What is the most efficient way (time-wise) to count number of posts returned from a query and parse the posts returned?
PART 1:
I currently 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 have no use for the other data this second get_posts($query)
-provides me with, how can I speed that up? I only need to count the total number of posts returned by the query (except the numberposts
-value.
PART 2:
The $lastposts
-object will be used later to get post data (ID, date, title, comment count, thumbnail and author ID).
These datas are inputed into the $print
-array like 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;
}
Is there a more time-efficient way to do this? I have noticed that the image-actions do take quite some time.
Thanks alot!
For part one you could create a new WP_Query object rather than using get_posts
. This should be more efficient than the code in your question, but the difference is likely to be negligible.
$query = new WP_Query();
$query->query(array(
'posts_per_page' => 15
));
$print['returnedcount'] = $query->post_count;
$print['totalposts'] = $query->found_posts;
Could you populate an array with what you need the first time the query is run - that would make running get_posts()
unnecessary.
So, in your template files you have
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;
You could move the whole data collection bit to functions.php. Are you using caching too? That might help. (e.g. http://wordpress.org/extend/plugins/hyper-cache/)
精彩评论