php function calculate Age
J V
<?php
// Рассчитать возраст по датам YYYY-MM-DD. Возвращает int или null.
function my_calculate_age($birthDate, $deathDate) {
if (empty($birthDate) || empty($deathDate)) return null;
$b = DateTime::createFromFormat('Y-m-d', $birthDate);
$d = DateTime::createFromFormat('Y-m-d', $deathDate);
if (!$b || !$d) return null;
if ($b->format('Y-m-d') !== $birthDate || $d->format('Y-m-d') !== $deathDate) return null;
if ($d < $b) return null;
return (int)$d->diff($b)->y;
}
// Общая функция сохранения возраста в метаполе поста
function my_wpuf_save_deceased_age($post_id) {
if (empty($post_id) || wp_is_post_revision($post_id)) return;
$birth = isset($_POST['birth_date']) ? sanitize_text_field($_POST['birth_date']) : '';
$death = isset($_POST['death_date']) ? sanitize_text_field($_POST['death_date']) : '';
$age = my_calculate_age($birth, $death);
if ($age !== null) {
update_post_meta($post_id, '_deceased_age', $age);
} else {
delete_post_meta($post_id, '_deceased_age');
}
}
// Хуки WP UF 6.8.2 для создания и обновления поста
add_action('wpuf_after_post_create', 'my_wpuf_save_deceased_age', 10, 1);
add_action('wpuf_after_post_update', 'my_wpuf_save_deceased_age', 10, 1);
?>
Fahmid Hasan - APM | weDevs
Thanks for sharing the snippet! We’re currently in the planning stage of adding a predefined Date of Birth field with dynamic age calculation to WPUF’s registration and profile forms. It’s not released yet, but we’re actively exploring how to implement it natively.
From your code, it looks like you’re calculating an age value between two dates (birth_date and death_date) and saving it as post meta. Could you please share a bit more about what you’re trying to achieve with this snippet? Are you working on a specific use case like a memorial or biography form?
Understanding your goal will help us see if your scenario aligns with the upcoming feature or if it requires a different approach.
Thanks again for taking the time to share your idea!