0

I'm using this in my page template to display the 20 recent posts headlines from category number 8, 17, 23, 423

  <div id="horizontalTab">
   <ul class="resp-tabs-list">
     <li>Football</li>
     <li>Ice Hockey</li>
     <li>Basketball</li>
     <li>Tennis</li>
    </ul>
    <div class="resp-tabs-container">
     <?php $cat_array=array(23,17,8,423);
      foreach ($cat_array as $catid) {
       $args = array( 'category' =>$catid, 'numberposts' => 20 );
       $myposts = get_posts($args); ?>
        <div>
         <?php foreach($myposts as $post) { ?>
         <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br/>
         <?php } ?>
       </div>
     <?php } ?>
 </div>
</div>

But this code adds more than 15 database queries. Without this code page makes 26 db queries and with it 46. Is it possible to optimize?

  • But are the queries slow? Hundred lightweight queries might be faster in total than one heavy one. – Rarst Apr 20 '14 at 12:52
  • Do you require 20 posts from each category, or just 20 posts overall, from the four categories? – Steven Jones Apr 20 '14 at 12:53
  • @Rarst, how can I determine it fast or slow? Load time and memory usage are approximately the same in both cases (I mean timer_stop and memory_get_usage functions). Do you think I should not worry about the number of db queries? Sorry for my English. – Moskwin Apr 20 '14 at 14:56
  • Profiling performance is extensive topic. :) Let's put it like this - if you cannot notice/measure significant difference (where "significant" is completely up to you) is it worth spending time on writing more elaborate code for it? – Rarst Apr 20 '14 at 15:05
  • @Rarst All the fault of the pursuit of excellence and limited my knowledge of php :) I guess you're right :) – Moskwin Apr 20 '14 at 15:15
0

Instead of looping through each category and getting the posts for each, you can do it all in one query like this:

$categories = array('8', 17, 23, 423);
$args = array( 'category__in' => $categories, 'numberposts' => 20 );
$recent_posts = get_posts($args);

Cheers.

  • 20 posts from all categories is not the same as 20 posts from each category however. – Rarst Apr 20 '14 at 12:50
  • That's true but the way I interpreted the question was he wanted 20 posts overall. I will ask for clarification in the comments. – Steven Jones Apr 20 '14 at 12:53
  • @StevenJones I want to display the 20 recent titles of the four specific categories – Moskwin Apr 20 '14 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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