Created
October 19, 2024 16:47
-
-
Save taricco/cd94893dc01f37d25c4da44dcc186c54 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** 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