0

I have a blog and on the main page are 3 blocks of posts. So, I get these posts with "get_post" and I have 3 similar codes on page:

global $post;
$args = array( ... );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); ?>
.......
<?php endforeach; ?>

I have a hight load of CPU and I wonder if I will use "wp_query" will save my CPU. Thanks.

Here are my get_posts() queries:

<?php
global $post;
$args = array( 'numberposts' => 5, 'offset'=> 0, 'category' => "1"   );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title(); ?>
</div>
<?php endforeach; ?>

<?php
global $post;
$args = array( 'numberposts' => 7, 'offset'=>0, 'category' =>"2 , 4 , 6 , 7 , 9 ,10,11");
$myposts = get_posts( $args );

foreach( $myposts as $post ) :  setup_postdata($post); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_post_thumbnail(array('size' => 300,300), array('title' => '')); ?>
</div>
<?php endforeach; ?>

<?php
$args = array( 'numberposts' => 15, 'orderby' => 'rand' ,'offset'=>0, 'category' =>"31");
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); ?>
<?php the_title(); ?>
</div>
  <?php endforeach; ?>
2
  • Do you have still high CPU load when you comment out these loops/queries?
    – Tom J Nowell
    Jan 4, 2013 at 15:35
  • I will try this Jan 4, 2013 at 17:38

2 Answers 2

2

I doubt using get_posts() vs WP_Query() would make any meaningful/noticeable difference in CPU load. Ultimately, get_posts() is just a wrapper for WP_Query(), anyway:

$get_posts = new WP_Query;
return $get_posts->query($r);

You would be better served by looking at the efficiency of the queries themselves; but to provide specific assistance there, we would need to see each of your get_posts() queries.

0
2

All queries are eventually wrappers of WP_Query, and while some are better than other ( never use query_posts ), the performance differences of get_posts vs WP_Query are negligible.

The strict answer would be that WP_Query is faster, but the margin by which it's faster imperceptably small as to not be worth the optimisation.

If you have high CPU load, switching between get_posts and WP_Query is not the solution

I recommend viewing this slideset by the core developer Nacin that explains when and how queries should be used, and why:

http://www.slideshare.net/andrewnacin/you-dont-know-query-wordcamp-netherlands-2012

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.