How is WP_Query connected to WP_Post in The Loop?

Yes, an object containing other objects is “natural”. A House object contains an array of Furniture objects in its $furnitures property… Such as in our case… WP_Query contains an array of WP_Post objects in its $posts property… A one-to-many relationship. This is an Aggregation.

OOP is all about programatically modelizing things. These things are:

  • From the system context, data and process.
  • From the real world context, entity and logic.

These 2 contexts are relationnal. The data is defined by its entity and the process is defined by its logic. These 2 contexts are then transmutable into a common programming pattern – OOP…

The WP_Post object is an entity holding and defined by – its data. It’s what we call a Domain Model Object. Though, since it doesn’t include any Domain Logic, design purists may call it an Anemic Domain Model Object instead.

The WP_Query object is a process (service). In fact, it is defined by the domain logic of our WP_Post object with for example:

$the_query->have_posts();
$the_query->the_post();

The WP Loop itself iterates through the WP_Query::$posts and is in charge of switching context (the global $post object).

From within The Loop:

  • WP_Query::the_post() initializes the global $post. You then can access the $post data via, for example, get_the_ID() or $post->ID.

  • WP_Query::have_posts() checks if there are other WP_Query::$posts to iterate through.

tech