0

I think I have understood most of how to create my own themes but this one thing: How can a loop in say page.php know which page to view when it loops through all the pages on my site? If I load one of my single pages (ex. contact form) how does page.php knows that it should only load that one specific page when it loops through all of them?

  • And the reason my page.php loops through all the pages is because the default themes have their page.php which does it. And it seems nice. I just dont understood how it works.. – KAS Oct 17 '15 at 22:12
1

Your loop on page.php doesn't loop through all the pages on the site. It loops though all the pages returned by the main query and stored in the $wp_query global variable, which is how all of the primary WordPress "pages" work including the post archive pages, category, tag pages, etc. For any one "page" only one page will be in the $wp_query global so you only see one.

While the details can get complicated, what happens with a page load in WordPress is that the WP_Query class gets instantiated fairly early and it parses the url being loaded and works out what posts to query. That information is shoved into the wp_query global variable and is accessed by numerous bits of code thereafter (which is why you don't really ever want to alter that variable manually or via query_posts()). It is a wildly complicated mechanism which you can see here: https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/query.php#L1448

| improve this answer | |
  • Thank you so much, this was very helpful! Have a nice day! – KAS Oct 18 '15 at 7:19
  • @KAS if you found this answer helpful, and it solved your issue, you should consider accepting this answer by clicking on the checkmark next to this answer below the up and down arrows. It will turn green meaning that the answer is accepted as the most correct one ;-) – Pieter Goosen Oct 18 '15 at 9:27
0

A shorter/simplified version of @s_ha_dum's answer.

Running the templates to do the actual outputting of the HTML is the last thing wordpress does. Before getting there, wordpress parers the URL and based on that it determines the specific content that will be displayed. It is not really open ended, although plugins can extend the loop to do any weird stuff, it is fully determined based on the URL.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.