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

Ability to deactivate licence domains within MasterPress account management

25th October 2024

We have just rolled out an account management feature which allows licence holders to have better control over the domains that use their licence key. From the MasterPress Account Management page, the list of Active Sites that use your licence now includes a function that allows you to remove a domain from your licence. Simply… 

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