wordpress WP_Query vs query_posts vs get_posts

wordpress WP_Query vs query_posts vs get_posts

WordPress tutorial, wordpress WP_Query vs query_posts vs get_posts. There are three ways for fetching data(posts) from wordpress. query_posts  more often than others. But I prefer to use WP_Query(). WP_Query is object base more secure then others.

wordpress WP_Query vs query_posts vs get_posts

wordpress WP_Query vs query_posts vs get_posts
wordpress WP_Query vs query_posts vs get_posts

query_posts() is overly simplistic and problematic way to to modify main query of 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 pagination). Any modern WP code should use more reliable methods, like making use ofpre_get_posts hook, for this purpose. TL;DR don’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, less restrictions, also safe to use anywhere.

The basic difference is that query_posts() is really only for modifying the current Loop. Once you’re done it’s necessary to reset the loop and send it on its merry way. This method is also a little easier to understand, simply because your “query” is basically a URL string that you pass to the function, like so:

query_posts(‘meta_key=color&meta_value=blue’);
On the other hand, wp_query is more of a general purpose tool, and is more like directly writing MySQL queries than query_posts() is. You can also use it anywhere (not just in the Loop) and it doesn’t interfere with any currently running post queries.

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.