Handling data from date picker fields in WordPress
When building a CMS website for clients, it’s important to provide a user-friendly experience.
I was recently working on a project where a client could create an event for their website. Using the WP Types plugin, I added a date picker field into the custom post type. Great, right? The user can select a date and a time in 24 hour format.
As you can imagine, I wanted to order the events by the date entered in the date picker, with the most recent event coming first. However, the data returned was the following:
Obviously, this wasn’t the most ideal return value. After some research, I realised this was a Unix time-stamp and I needed to do some pre-processing of the variable before rendering it on the front end.
Processing the data
Essentially, you need to create a new DateTime object with the variable and use the createFromFormat method. We specify the format as ‘U’ for Unix time-stamp.
<?php $d = get_post_meta(get_the_ID(), 'wpcf-date-of-event', true); $date = DateTime::createFromFormat('U', $d); ?>
Then you have to format your variable to a human readable format.
<?php $date = $date->format('jS F'); ?>
Handling the time
I wanted to display the date and time separately (next to nice icons) so I just split out the variables and my final script looked like this.
<?php $d = get_post_meta(get_the_ID(), 'wpcf-date-of-event', true); $date = DateTime::createFromFormat('U', $d); $time = DateTime::createFromFormat('U', $d); $date = $date->format('jS F'); $time = $time->format('H:i'); ?>
Why use a DatePicker field at all?
You may argue that providing two single fields for the date and time would’ve been easier. I would argue that you want to provide a user-friendly, reliable and intuitive CMS. Users are very used to using a date picker to enter dates. Any potential user experience issues you can iron out before delivering a website will save you time dealing with enquiries in the future.
It is also important to pass the appropriate data type. This method ensures you are passing date and time variables instead of plain text fields which, hopefully, will eliminate any potential ordering problems and further unnecessary parsing.
Get in touch
If you can save me a few lines of code, I always appreciate a good suggestion. I’m sure there’s a way to not have to create a separate date and time variable and still render them separately. As always, please get in touch via twitter or email me.