When to use WP_Query, query_posts and pre_get_posts

  • query_posts() function is commonly thought of as the simplistic and problematic way forward to modify a main query of a page by replacing it with a new instance of the particular query. It is bad practice as it re runs SQL queries and will simply not work and fail in some circumstances, this usually happens when dealing with post pagination. In the older versions of plugins and themes, this method will seen more, but it is strongly advised that any modern WP code should use more reliable methods; such as utilising the pre_get_posts hook.
  • get_posts() function is a similar way to query in terms of usage and it accepts the same arguments with some minor differences such as the defaults of the query. It stil returns an array of posts but the important thing to remember is it doesn’t modify global variables and it is safe to use anywhere.
  • WP_Query object drives both of the above queries behind the scenes, but you can also create and work this object on it own. It can be considered a little more complex as it has less restrictions and can have more possibilities, this object, as above is safe to use anywhere.

 

Original – Link

Leave a comment

Your email address will not be published. Required fields are marked *