This article is for beginners of WordPress themes. The difference between the WP_Query vs query_posts vs get_posts is elaborated as follow:
query_posts
query_posts()
is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts
hook, for this purpose. TL;DR don’t use query_posts() ever;
get_posts
get_posts()
is very similar in usage and accepts same arguments (with some nuances, like different defaults), but returns array of posts, doesn’t modify global variables and is safe to use anywhere;
WP_Query
WP_Query
class powers both behind the scenes, but you can also create and work with own object of it. Bit more complex, less restrictions, also safe to use anywhere.
Conclusion
The get_posts will create an array of posts based on the parameters defined. It will retrieved the list of the recent posts matching the criteria.
get_posts can also be used to create multiple loops however WP_Query is preferred method for using Multiple Loops. Also get_posts uses WP_Query as evident from the table above
<?php $args = array( 'posts_per_page' => 5, 'offset' => 0, 'category' => '', 'category_name' => '', 'orderby' => 'date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'post', 'post_mime_type' => '', 'post_parent' => '', 'author' => '', 'post_status' => 'publish', 'suppress_filters' => true ); $posts_array = get_posts( $args ); ?> Note: 'numberposts' and 'posts_per_page' can be used interchangeably.
Parameters
Note: The category parameter needs to be the ID of the category, and not the category name.
Note: The category parameter can be a comma separated list of categories, as the get_posts() function passes the ‘category’ parameter directly into WP_Query as 'cat'.
Note: The category_name parameter needs to be a string, in this case, the category name.
Note: The posts_per_page parameter does NOT work without setting the offset parameter.
Example
You can use the code below to show three posts using the following code.
<?php
$args = array( 'posts_per_page' => 3, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endforeach;
wp_reset_postdata();
?>
Breakup of the above code is as follow:
We have defined a variable to store our parameters or arguments “$args”
Then we used the get_posts function to set the parameters by passing the $args variable.
Then using the for loop, we retrieved the posts and have shown there link and title using the the_permalink and the_title.
Lastly we ended the loop and reset the posts data.