What is the difference between WP_Query, get_posts() and query_posts()?
| Method | What it does | Use? |
|---|---|---|
| WP_Query | Class. Makes a new query object, and gives you the loop, pagination and many properties | Yes, for custom loops |
| get_posts() | Function. Returns a simple array of posts. No loop setup, no pagination | Yes, for simple lists |
| query_posts() | Replaces the main query, and breaks pagination and conditional tags | No, never |
| pre_get_posts | Hook. Changes the main query before it runs | Yes, for the main query |
// get_posts(): an array of post objects, no loop setup
$posts = get_posts( array( 'posts_per_page' => 2, 'post_type' => 'post' ) );
foreach ( $posts as $p ) {
echo $p->ID . ' ' . $p->post_title . "\n";
}
// WP_Query: a loop with the helper methods
$q = new WP_Query( array( 'posts_per_page' => 2 ) );
echo 'Total found: ' . $q->found_posts . ', pages: ' . $q->max_num_pages;
Output
6 Third post
5 Second post
Total found: 3, pages: 2
get_posts() also sets suppress_filters to true by default, so some plugin filters do not run. To change the main query use pre_get_posts, see WP_Query.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |