Being careful with the $post variable
A common code pattern when retrieving multiple objects in the MasterPress API is the use of the foreach loop on the result of a multiple object querying method. Consider if we had the following code before the main post output in our single.php template, to run a secondary query to show a list of featured posts taken from a related post field in a “Home Page” site field set:
Example 1: The best intentions
There’s nothing particularly unusual about this example – we have the boilerplate code for a loop at the top of our template, and we place a secondary loop within that using the an iterator on the featured_posts field to show our featured posts. But this code will have problems when we render the post being viewed, and the code won’t throw an error message, but just behave strangely.
There’s a couple of issues here:
- We’ve used the $post identifier for our loop variable on line 6. This is problematic, because WordPress has a global variable $post that it uses to track the current post being viewed.
- Our secondary loop should really come before line 1, so that the $post variable isn’t interfered with. This is probably obvious to experienced WordPress developers, but not so obvious for beginners.
Don’t use $post in foreach, use $the or something else!
The easiest way to avoid issues like this is to simply avoid using the identifier $post for your loop variable. You may have noticed that many examples throughout this documentation use $the instead, which not only avoids clashes, but actually reads pretty well too:
Example 2: Rewriting our foreach to use $the
Because we now access properties on $the our loop resembles the standard WordPress template tags like the_title(), the_excerpt(), and so on. Note that we could have also used $feature quite happily in this example too.