Problem:
The customer created a Custom Post Type (CPT) with a date field and wanted to allow users to filter posts by month and/or year using a select list. The Toolset view filters did not support filtering by only month or year because the date field is queried as a timestamp.
Solution:
We explained that it’s not possible to filter by month or year directly using Toolset’s default date field filters. As a workaround, we suggested creating separate custom fields for the month and year, which could then be used in the filter. We provided a code example using the save_post hook to automatically populate these custom fields based on the selected date whenever a post is created or edited:
function auto_generate_month_year_from_date_field($post_id) { // Check if it's the correct post type if (get_post_type($post_id) == 'YOUR_POST_TYPE') { // Retrieve the date field $date_field = get_post_meta($post_id, 'wpcf-YOUR-CUSTOM-DATE-FIELD-SLUG', true); if (!empty($date_field)) { // Convert the timestamp to a DateTime object $date_obj = DateTime::createFromFormat('U', $date_field); // Check if date creation was successful if ($date_obj) { // Extract the year and month $year = date_format($date_obj, "Y"); $month = date_format($date_obj, "m"); // Update the custom fields with year and month update_post_meta($post_id, 'wpcf-YEAR-FIELD-SLUG', $year); update_post_meta($post_id, 'wpcf-MONTH-FIELD-SLUG', $month); } } } } add_action('save_post', 'auto_generate_month_year_from_date_field', 101);
Relevant Documentation:
https://toolset.com/course-lesson/filtering-toolset-views-by-dates/
https://developer.wordpress.org/reference/hooks/save_post/
https://developer.wordpress.org/reference/hooks/save_post/
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | 9:00 – 12:00 | 9:00 – 12:00 | 9:00 – 12:00 | 9:00 – 12:00 | 9:00 – 12:00 | - |
- | 13:00 – 18:00 | 13:00 – 18:00 | 13:00 – 18:00 | 13:00 – 18:00 | 13:00 – 18:00 | - |
Supporter timezone: America/Sao_Paulo (GMT-03:00)
This topic contains 5 replies, has 2 voices.
Last updated by 3 months, 3 weeks ago.
Assisted by: Mateus Getulio.