Storing dates in post meta enables easy grouping of posts into current, future and past. This automatic grouping simplifies the client workflow and helps site visitors.
I am working on a project where the client runs multi week training courses. They were manually setting whether courses were past, current and forthcoming and generally forgetting to update the setting. I wanted to make it automatic.
Keep the workflow
The client was using post categories to highlight current or forthcoming courses and past courses. Unfortunately setting these categories is a manual exercise and maintaining them was a very low priority so it was rarely up to date.
Initially I thought about creating a WordPress cron task to add or remove the appropriate categories but I find wp-cron tasks difficult to debug so I began thinking of a more flexible solution.
Use CMB2 for the course dates
The current course posts list the starting date in the post content but this is not useful for automated operations. I used CMB2 to create two date fields. I used the ‘text_date_timestamp field type as it stores a Unix timestamp number (seconds since the epoch) which is very easy to work with.
The field uses a date picker so it is very easy for the post editor to use.
And here’s how it displays in the Edit Post screen:
Display course dates
I display the course dates at the top of the post. It’s very simple code. I am using a StudioPress Genesis theme hence the ‘genesis_entry_content‘ action. A more generic version would use ‘the_content‘ filter.
And it shows between the post date and the content:
Sort into Current, Forthcoming and Past
I implemented the post list as a shortcode. I felt that this made it easier to use (and easier to code). I didn’t want to hard code a page slug into the code to determine where the posts would be displayed as the client might change them in the future. The client only need specify the category slug.
The WP_Query() call retrieves all posts as I know that there will never be too many of them. For each post I compare the post meta start and end dates to the current date and append the post into one of three arrays – current, forthcoming and past. The text with the dates is different e.g. “Runs X until Y” for forthcoming courses, “Started: X, ends Y” for current courses and “Ran X until Y” for past courses.
At the end I add a h3 header before each section, combine the post lists and sections and return them for display.
I realise that it doesn’t sort within each array – a possible enhancement could be to set the array index to the start date and then sort by start date when joining the array elements together. As site visitors will generally look for courses based in their area rather than by date so having one or two dates to appear to be out of order won’t be a problem.