Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save taricco/cd94893dc01f37d25c4da44dcc186c54 to your computer and use it in GitHub Desktop.
Save taricco/cd94893dc01f37d25c4da44dcc186c54 to your computer and use it in GitHub Desktop.
/*** Custom template tag for styling an ACF date/time field (IMPORTANT, this works for the ACF Date/Time field only)
Set ACF date/time field return format to: Ymd H:i:s
Tag format: {{datetimeformat.event_start|M j, Y | g:i a}}
–––––––––––––––––––––––––––––––––––––––––––––––––– ***/
add_filter("render_block", "wsv_date_time_format_tags", 11, 2);
function wsv_date_time_format_tags($block_content, $block) {
// Updated pattern to match {{datetimeformat.<field>|<format>}} and allow the | character in the format
$pattern = "/{{datetimeformat\.([\w-]+)\|([,\w\s:-\|]+)}}/";
$new_content = preg_replace_callback($pattern, function ($matches) {
if (!function_exists("get_field")) return $matches[0]; // Ensure ACF is active
$field_name = trim($matches[1]);
$format = $matches[2];
$field_value = get_field($field_name);
// Check if the field value is available and not empty
if ($field_value) {
// Handle both date and date-time formats
$date_format = strpos($field_value, ' ') !== false ? 'Ymd H:i:s' : 'Ymd';
// Attempt to create a DateTime object
$date = DateTime::createFromFormat($date_format, $field_value);
if ($date !== false) {
// Return the formatted date or time
return $date->format($format);
}
}
// If no valid date or time, return the original tag
return $matches[0];
}, $block_content);
return $new_content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment