Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taricco/2481c2101bf1f837fc9948a7d5f70760 to your computer and use it in GitHub Desktop.
Save taricco/2481c2101bf1f837fc9948a7d5f70760 to your computer and use it in GitHub Desktop.
/*** Custom template tag for styling an ACF date field
Tag format: {{dateformat.field_name|D M j}}
–––––––––––––––––––––––––––––––––––––––––––––––––– ***/
add_filter("render_block", "wsv_date_format_tags", 11, 2); // Note the priority is set to 11, to ensure it runs after tct_template_tags
function wsv_date_format_tags($block_content, $block) {
// Updated pattern to allow a broader range of characters in the format, including commas, spaces, and common date format characters
$pattern = "/{{dateformat\.([\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);
// Attempt to convert the ACF field value to a DateTime object
if ($field_value && ($date = DateTime::createFromFormat('Ymd', $field_value))) {
// If conversion is successful and a format is specified, format the date
return $date->format($format);
}
// If conversion fails or there's no field value, return original tag (or consider returning an empty string or a fallback message)
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