I was trying to find out how wordpress process each request and returns the result. I found wp()
function calls $wp->main()
which in turn calls $this->query_posts();
and which calls $wp_the_query->query($this->query_vars)
function in query.php
file. The query()
function calls return $this->get_posts();
and return the result.
My question is didn’t see any any variables receiving this returned value so why this function has return, even though the wordpress works if I remove the return from the code. so what is the purpose of this return, (I guess this code saves the contents (posts) to $this->posts
variable). btw I am using wp 3.6
I believe this answer may provide what you’re looking for:
https://wordpress.stackexchange.com/a/1755
Specifically this image (which I did not create myself):
The use of return is related to
php
(also used in other languages) not onlyWordPress
. When execution reaches areturn statement
, the function stops and returns that value without processing any more of the function. Areturn
with no value returns null and If there is noreturn
keyword at the end of a function then, in this case too, anull
value get returned.Using a
return
statement at the end of a method/function is a good coding practice, it just returns the execution control back to the point, from where it started and it also Prevents Code Injection in PHP include files. Also, check this.Short Answer:
There are other functions that make use of the returned value, mostly in themes and plugins, but also in WP core. examples are given below.
Long Answer:
In wordpress the WP_Query::query() method is used for getting posts from the DB.
This is done by providing certain criteria for selection, ie: the query_vars.
Based on which the posts are retrieved and made available.
now, in the case mentioned by you what is of important is the call stack, ie the path used to call the function.
ie:
In WP->main(), the parse_request methond is called, which creates the query_vars from the REQUEST_URI.
so whatever post is fectched depends on the requested pages URL. i.e the criteria for selection is provided by the requested page’s url.
And since the query method is called on the global wp_query object, there is no need to return it.
This forms the main path, ie: global wp query, and request uri query vars.
But in cases, like in themes, plugin, when you need to fetch additional posts. you will create a new wp query object, and use the query method.
eg: to fetch all posts by ‘john’. in these situation the value returned by the query method is used.
Some functions that uses it: