This code works, and I want to understand why.
So I created the object from the WP_Query
class, and used the have_posts()
and the_post()
functions in a while loop.
The question is: since the $post->ID
is a data in an array based on the class WP_Post
would this than mean that the object instantiated from the WP_Post
class is inside the object instantiated from the WP_Query
class?
Can an object be inside one another? Or am I missing something?
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php echo '<p>' .$post->ID .'</p>';?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p>No-data!</p>
<?php endif; ?>
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.