Forked from taricco/Custom template tag for formating an ACF date field.php
Created
April 22, 2025 07:54
-
-
Save infocities/8e41763f2cfcd1a37e4a716466b7dc3d 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 field (IMPORTANT, this works for the ACF Date field only) | |
Set ACF date field return format to: Ymd | |
Tag format: {{dateformat.field_name|D M j}} | |
–––––––––––––––––––––––––––––––––––––––––––––––––– ***/ | |
add_filter("render_block", "wsv_date_format_tags", 11, 2); // Updated function name | |
function wsv_date_format_tags($block_content, $block) { | |
// Updated pattern to allow commas, spaces, common date format characters, and the pipe (|) character in the format | |
$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 the 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