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: