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.2.8 is now available

It was brought to our attention that MasterPress would give a tonne of warnings and deprecation notices when used with PHP 7.4 – this update addresses those.

Plugin Requirements

MasterPress requires a minimum of WordPress version 4.9, MySQL 5.6, and PHP version 5.6.20.

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.

Three AM