get posts vs new wp_query in wordpress theme

get posts vs new wp_query in wordpress theme

For getting the wordpress posts we use the following methods. In every wordpress theme we always use the get_posts() vs WP_Query vs query_posts() methods for creating the wordpress theme. We should know about wordpress methods first.

get posts vs new wp_query in wordpress theme

 

  • 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 ofpre_get_posts hook, for this purpose. TL;DRdon’t use query_posts() ever;
  • 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 class powers both behind the scenes, but you can also create and work with own object of it. Bit more complex, fewer restrictions, also safe to use anywhere.

As per my opinion you should use the WP_Query() method. This is secure to use. If you have a choice, go with WP_Query. Both of the other functions (query_posts() andget_posts()) call WP_Query indirectly.

get posts vs new wp_query in wordpress theme
get posts vs new wp_query in wordpress theme

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.