How does post loop integrate individual page elements

How a posts template gets loaded:

  1. You visit a WP site at a URL, /abc/xyz
  2. WP doesn’t process pretty permalinks directly, it translates them into the form index.php?var=value internally, so it runs them through all the rewrite rules until the first one matches, if none match, it’s a 404 and 404.php is loaded.
    • This is where pretty permalink URLs come from.
  3. The rewrite rule maps /abc/xyz into a URL of the form index.php?foo=xyz where foo is a query variable, the kind that goes into a WP_Query. foo is just an example, for a list of valid parameters see the WP_Query documentation
    • This WP_Query object is the main query that powers the post loop.
    • The user and browser never actually see this, there are no redirects or “rewrites” in the classic sense.
  4. WP looks at this query and makes some decisions, is it a post archive? is it a page? a singular post? It then uses this to setup flags that power is_single() or is_search()
    • This also means that all URLs in standard WordPress on the frontend have a post loop/query, and are either archives of multiple posts, or single post queries
  5. Run some filters, pre_get_posts, etc, so that the query can be changed before stuff happens
  6. To the database! Fetch the posts!
  7. Now that we have posts, use that WP_Query and all the parameters and flags to decide which template to load. ( see the template hierarchy diagrams ). This is how WP will decide which theme file displays the post loop.
    • Notice that the posts have already been fetched from the database.
    • index.php is the fallback which is why it’s the only mandatory PHP file in a theme.
    • you can’t change the main query from inside a theme template because the main query has already happened, it’s too late
  8. Load the theme template we decided on in the previous step. This template should have a standard post loop, and this is what displays the posts, through functions such as the_title and the_content.
    • Notice that the post loop does not fetch posts from the database, that happened before WP even chose the template. It is just providing you an opportunity to display the information

The ultra short version:

  • URL + rewrite rules = query vars
  • main query = new WP_Query( query vars from previous step )
  • look at main query and pick a template based on it, e.g. if main query->is_search() pick search.php, etc
  • load template to display the posts that got fetched

Post content and a theme may enqueue some javascript, and post content itself is taken from the database, with some filters ran over it. There is also the shortcode system and the dynamic blocks system. Each of those are independent systems in their own right.

Also remember that at the end of the day the final result of a block is still just HTML content that gets saved in the post content column of the database.

This is the basic high level architecture of a page load.