This quite a broad question to answer. I’m not going to go into detail here and into core code, you’ll need to go and read the links I’m going to provide. I’m going to try to keep my answer sweet and short and useful 🙂
Take the bundled theme twentyfourteen for example, when you open any page template, you’ll find this piece of code
if( have_posts() ) :
while( have_posts() ) : the_post();
<----loop elements---->
endwhile;
endif;
This is your loop, which basically displays the queried information from the main loop on the spesific template. That is all the loop does, it displayes what is retrieved by the main query (or custom query if there is one).
What to display where is decided by the Template Hierarchy. WordPress relies heavily on this hierarchy structure. If you have a look at how the main query works, ( go and read Query Overview) you’ll see that the main query uses this template hierarchy to decide which template to use and what information to retrieve from the database, this is why the information will be diffirent for, lets say, category.php and author.php, although your loop is exactly the same as you say
As per your question
Why is it that 2, identical php file produce different results? In my example, the “sample-page.php” will display the “PAGE CONTENT”, while “home.php” will display “RECENT POSTS”
The abovementioned info basically covers this part, aswell, the main query uses post_type=page
when it makes a query on page templates, and post_type=post
on home.php, that is one of the big differences
Why do we need, “while” loop, if all we want is to display the “PAGE CONTENT”
The while()
loop is not necessary on page templates. You’ll only have one post to display.
If we want to show “RECENT POSTS” in a template page. Why do we need to provide some queries first?
By default, the main query queries post_type=page
for page templates, not post-type=post
. That is why by default you cannot display “recent posts” on pages. For this you’ll need to run a custom query with WP_Query
or alter the main query using pre_get_posts
EDIT
You can also go and have a look at my answer for further info