8

I have read a number of questions on SE regarding these but I still can't figure the exact difference wrt usage. Would it be true to say that I would probably use WP_Query for the majority of secondary loops and only use get_posts if I need the results returned in an array, or to put it another way is the main difference between the two the array vs object return, or is there some other major factor I should be aware of?

2 Answers 2

18

The difference between get_posts & WP_Query

You can view get_posts() as a slimmed down WP_Query. In fact looking at the source:

//... prepares query array $r
$get_posts = new WP_Query;
return $get_posts->query($r);

get_posts() use WP_Query, but only returns an array of posts - nothing more. Furthermore it sets:

$r['no_found_rows'] = true;

Normally (by default with WP_Query object) - WordPress queries how many posts there are in total - even if you are only after the first 10. It does this so it can perform pagination. So get_posts() is actually (slightly) quicker (it also ignores sticky posts).

Which to use...

If you only need an array of posts, and don't need the query object -use get_posts(). Otherwise, if you do need the access to the query object methods, or pagination, or sticky posts at the top, you should use WP_Query.

2

One important thing to note is that get_posts() has a bunch of default arguments that new WP_Query() doesn't have, which include post_type and post_status. The function's defaults are configured to facilitate getting published posts. If you want something different, you'll need to pass in thos parameters explicitly, whereas with WP_Query() you wouldn't have to do that.

For example, if you want to get all posts, regardless of their post status, you would need to call: get_posts( array( "post_type" => 'any' ) ); (leaving "post_type" blank - or anything that empty() would evaluate to true will cause get_posts() to apply its default value of "publish").

3
  • 1
    WP_Query has those same post type and status defaults.
    – Milo
    Commented May 8, 2017 at 23:23
  • @Milo Are you sure? Look at class-wp-query.php lines 1742 - 1746. I believe the default for post_type is "", or "any" for tax queries. The docs seem to support this as well.
    – Tom Auger
    Commented May 10, 2017 at 18:01
  • Post type defaults to any in certain circumstances, like a search or some tax queries. Run a new WP_Query and pass only posts_per_page, it will default to post.
    – Milo
    Commented May 10, 2017 at 18:11

Your Answer

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

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