Working with field values

One very nice aspect of the MasterPress API is in its clever use of the PHP magic method __toString method to allow custom field values to be directly echoed to your templates to giving you appropriately formatted HTML. Take a custom field to store an image, for example. In standard WordPress, you might have written code like this:

Example 1: The WordPress way, with get_post_meta

That is, the thumb field is a custom field that stores a URL to the image, and you output that inside the “src” attribute. MasterPress is a bit smarter than that – since it knows your field is an image, you can write code like this, which generates the image tag for you:

Example 2: The MasterPress way

Note that because our image field is an object, we can use the URL property of the image field to output the tag too, if you really need to:

Example 3: Manually outputting HTML

As you get accustomed to this, you may start to think that the API can read your mind, and you can just use these field objects anywhere – but there’s a gotcha…

Field expressions

Now suppose we have an Event post type, with a field set “details” and a “start_date” date field. We might write code like this in the single-event.php template:

Example 4: Good luck buying tickets...

Nothing looks particularly wrong here – we check to see if the date is in the future by seeing if it’s greater than the current time. The problem is that we’re not comparing what we think we might be – this is what we’re trying to do here:

Example 5: Apples and Oranges

What we should do is use the “value” method, which generally returns the stored value of the field, but in the case of Date Picker, is overridden to return the timestamp value. Here is the correct code:

Example 6: Using the value method

This is an easy trap to fall into, so be careful.

It’s not all doom and gloom however – one of the nice things about fields being objects rather than basic literal values, is that field types can provide their own mini-APIs. If you look at the documentation for the MPFT_DatePicker class, you’ll see another method that can make our code even more concise:

Example 7: Back to the Future

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 hosted service.

Three AM Web + IT