WordPress – is get_posts() more efficient than The Loop?

In category.php, I want to get list of posts in that category.

I found two ways: using get_posts($args) and The Loop.

Read More

get_posts() way

$args = array (
  "category" => ID );
$posts = get_posts($args);
// then use foreach to loop the $posts

The Loop way

<?php if (have_posts() ): ?>
  <?php while (have_posts() ): the_post(); ?>
    ...
  <?php endwhile; ?>
<?php endif; ?>

So which one is more efficient?

From what I have found in searching, get_posts() is for custom templates while The Loop is used inside the template that follows the WordPress naming convention.

I prefer get_posts(), but if there’s a big overhead compared to The Loop, I should re-think it again.

Related posts

Leave a Reply

1 comment

  1. I finally found the answer.

    When we open a page using the right template (template that follows the naming convention), WordPress automatically do query to get all the relevant posts or content

    So if I use $posts = get_posts($args);, it means I do additional query which is unnecessary.

    $posts = get_posts($args); should only be used outside template for example on sidebar that always be there on every pages.