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:

  1. 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.
  2. 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.

Latest From the Blog

MasterPress 1.1.4 now available

MasterPress 1.1.4 is now available. This release contains an important compatibility fix for WordPress 4.5 to allow correct detection of the taxonomy term editing screen. Without this fix, any custom fields you have attached to custom taxonomies will not be shown at all in the editing form. Note also that MasterPress will still detect the edit screen correctly in… 

Plugin Requirements

MasterPress requires a minimum of WordPress version 3.4, MySQL 5, and PHP version 5.2.4.

We also recommend that PHP is configured to use a memory limit of 64MB per request (128MB may be required for sites with higher complexity).

This plug-in is not compatible with the WordPress.com hosted service.

Traversal