Mike Cho Development

Print a custom field in WordPress

Let’s suppose you:

Have already created a custom field

Want to print it on a page template somewhere

Use this as a model:*

echo date('l F jS, Y', strtotime(get_post_meta(get_the_ID(), 'event_date', true)));

This complicated little morsel uses nested functions to 1) obtain, and 2) format a custom field called Event Date, referred to here by its “machine name,” event_date.

The wrapping date() function takes a timestamp and formats it according to the string that’s the first argument. l F jS, Y tells PHP to spit it out as DayOfWeek Month DayOfMonth, Year, for example, “Friday April 2nd, 2021.”

get_post_meta is the heart of this construction: It retrieves the custom field associated with the particular post. The arguments it needs here are the ID, the name of the meta field, and whether to return a single value.

The name of the meta field is, as was already mentioned, the custom field (I used Advanced Custom Fields to add it), “event_date,” and the ID is produced by the get_the_ID() function.

See event_date under Name?

The return single value parameter I’m not sure about, but it works, so let’s go with it.

Put it in the archive

By creating an archive-events.php, WordPress automatically uses that to collect the events posts.

I now modify this with the line of code above. I’ll add a wrapper and some classes later.

*A better way

There’s an easier way to get the same information–without using the get_post_meta() function. You can get the same thing using the simpler construction $post->event_date.

echo date('l F jS, Y', strtotime($post->event_date));

This is shorter, easier to read IMO, and accomplishes the same thing.