Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 9, 2015 12:00 pm

Mastering WP_Query: Related Functions

Hi, and welcome to the second part of the series called "Mastering WP_Query". In the first part, we started off with the series by simply introducing what the WP_Query class is. And in this second part, we're going to learn about the functions related to WP_Query.



Let's begin!



Harnessing the Power of WP_Query With Functions, Actions and Filters



I'm not an expert on programming, but I can see that the WP_Query class is one of the best examples of the MVC pattern. It's extremely powerful, completely extensible, and very easy to use once you get to know the basics.



In addition to its properties, methods and parameters (which we're going to go through in the future), WordPress offers extra functions and hooks (meaning actions and filters) to work with the WP_Query class. In this tutorial, we're going to get to know the functions and in the next part, we'll see actions and filters related to WP_Query. If you see that I forgot something, feel free to notify me by shooting a comment.



WP_Query Related Functions



There are 13 WordPress functions that work with the WP_Query class that can help you harness the power of WP_Query. They don't need any introduction, so here we go:



Getting Public Query Variables: get_query_var()



Our first function's name speaks for itself, really: It takes the global $wp_query object and retrieves a public query variable from it. It has two parameters: The first one is the variable to return its value, and the second one is a default value to return if the variable is not set:





Affecting the Main Loop: query_posts()



To be honest, this is a bad function. You really don't have to use it at all, but for the sake of telling "the right way", we're going to go over it and tell you it's "the wrong way".



query_posts() is a function that alters the main query by putting the main query aside and running a new query—and you'll need to use wp_reset_query() to clean up after it.





This function is one of the most misused functions in the core of WordPress. You shouldn't use it to create secondary queries—you can use the WP_Query class or the get_posts() function (which we'll talk about later in this tutorial). You shouldn't use it to alter the main query either—you should use the pre_get_posts action (which we'll talk about later as well). Even the Codex discourages us from using it and shows alternatives.



Bottom line: Don't use it.



Getting a Single Post: get_post()



Another self-explanatory function is get_post(), which you use to get a single post. It has three optional parameters:




  • The first one is the post ID (or the ID of the current post by default).

  • The second one is the type of the result you'll get: either OBJECT, ARRAY_A (an associative array) or ARRAY_N (a numeric array).

  • The third one is the choice of filtering the result. The default is 'raw' so it won't be filtered unless you set it to 'edit', 'display', 'attribute' or 'js'.





Saving Queries to Arrays: get_posts()



The get_posts() function allows us to run queries and save them as arrays to use in various places. It requires the same arguments with WP_Query so you can customize the query as you like. (We'll get to review WP_Query's parameters in the future, so stay tuned!) It's the best and most efficient way to create post lists—but not loops.





Although this function can be used to run "secondary queries" without a problem, the Codex recommends using WP_Query when creating multiple loops and using get_posts() when fetching a post list. Peter R. Knight explains the difference between get_posts() and WP_Query in simple terms: The main difference is that WP_Query makes more database queries (post data, meta data, author data and comment data) while get_posts() makes only one query (post data).



Getting Pages: get_pages()



This odd function has the purpose of fetching a list of pages, although it has a post_type parameter that can also let you select another post type (provided that the post type is hierarchical, otherwise it returns false).





It accepts arguments that are very similar to WP_Query's arguments, but they're slightly different:





  • sort_order: Whether to sort the pages in an ascending (asc) or descending (desc) order.


  • sort_column: How to sort the pages. Accepts post_title, menu_order, post_date, post_modified, ID, post_author, and post_name.


  • hierarchical: Whether to list pages hierarchically (1) or not (0).


  • exclude: A comma separated list or an array of page IDs to exclude from the listing.


  • include: A comma separated list or an array of page IDs to include from the listing and exclude everything else.


  • meta_key: When used with the meta_value argument, it only includes pages that have the defined meta key and value.


  • meta_value: When used with the meta_key argument, it only includes pages that have the defined meta key and value.


  • authors: A comma separated list of author IDs.


  • child_of: An ID of a page to fetch only its children and grandchildren in the listing.


  • parent: List the pages that have the provided page ID as parent. In order for this argument to work, the hierarchical argument must be set to 0.


  • exclude_tree: A comma separated list or an array of page IDs to exclude with its children.


  • number: Number of pages to fetch.


  • offset: Number of pages to skip from the top.


  • post_type: The post type to query. Naturally, it defaults to page.


  • post_status: A comma separated list of post status types to include.



Checking Whether the Query Returns Posts: have_posts()



Without accepting any parameters, this function simply returns TRUE if the query returns any records and FALSE if not.





Working the Loop: the_post()



The Codex says that it "iterates the post index in the Loop". It does several things:




  1. It fetches the next record from the query.

  2. It sets up the $post data.

  3. It sets the in_the_loop parameter to TRUE.





Setting Up $post: setup_postdata()



This function also speaks for itself: It sets up the global post data. Let's see what the Codex says about this one:




setup_postdata() fills the global variables $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages, which help many Template Tags work in the current post context. It does not assign the global $post variable, but seems to expect that its argument is a reference to it.






Clearing the Current Loop: rewind_posts()



Yet another function whose name states its functionality: This function simply "rewinds" the Loop so that you can run it again later.





Resetting $postwp_reset_postdata()



This function resets the global $post variable back to the first post in the main query. It's better to use this one after a secondary query.





Resetting the Query: wp_reset_query()



This one should be used if the main query is changed (with the query_posts() function or the pre_get_posts action which we'll see in the next part) so that the main query can be reset.





Checking Whether Current Query Is the Main Query: is_main_query()



This one is a Conditional Tag that returns TRUE if the current query is the main query and FALSE if it's not. Simple, right?





Checking Whether We're in the Loop: in_the_loop()



Another Conditional Tag is in_the_loop() that simply returns TRUE or FALSE if your code is running inside the Loop or not.





End of Part Two



There you go—now you know (probably) all the functions related to WP_Query! Stay tuned for the next part where we'll learn about WP_Query related actions and filters.



Do you have any comments or anything to add to this part? Feel free to share your thoughts by commenting below. And if you liked the article, don't forget to share it with your friends!


Original Link:

Share this article:    Share on Facebook
No Article Link

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code