
Add CMB2 metabox to show a GP Premium Element in a chosen date range.
Over the last two years I have changed from using Genesis Framework to GeneratePress as my starter theme. GeneratePress has a premium plugin, GP Premium, that unlocks a lot of customisation controls. It also includes ‘Elements‘ to add content without code.
Elements uses
The docs give examples of page heroes, header and footer replacing. You have precise control over where the element is displayed e.g. everywhere, archives, pages, posts, individual pages or posts, and exclude with the same precision. Furthermore, you can control display based on the current user type or whether they are logged in or not.
But there is no date range control!
Use CMB2 to set a date range
In this post I use a hook to add some content and set it to show everywhere.
With CMB2 I add 2 date fields. The info is stored as a timestamp for easy comparison with the current time. The fields open a date picker to make the date selection easier and the field shows the chosen date in a readable format (dd M YYYY e.g. 7 Oct 2022).
The post type is set to ‘gp_elements
‘ to limit it to Elements pages. The metabox is displayed below the Settings/Display Rules metabox because GP Premium does not have a do_action()
that would allow adding it to the Display Rules tab.
generate_element_display filter
Before an Element is displayed the display rules are examined. The result of that examination is passed to apply_filters()
with ‘generate_element_display
‘ filter. This filter is called for each of the 4 Elements types so is a good one to intercept. We can then get the postmeta and examine it to determine whether to display the Element.
The code must handle when element is not date limited i.e. there is no postmeta data.
Note that there is no error checking about whether the end date is after the start date.
Leave a Reply