Skip to content

Instantly share code, notes, and snippets.

@ChMat
Created March 6, 2019 14:51
Show Gist options
  • Save ChMat/6da14ab2a8a5a0e3c9255f432ab02d4a to your computer and use it in GitHub Desktop.
Save ChMat/6da14ab2a8a5a0e3c9255f432ab02d4a to your computer and use it in GitHub Desktop.
Wordpress Theme : Show the Age of a Person
<?php
// Ajoute le shortcode [age date="jj/mm/aaaa"]
add_shortcode('age', 'chmat_age');
/**
* Retourne l'âge d'une personne suivant la date de naissance fournie au format jj/mm/aaaa.
*
* Exemple :
*
* < ['date' => '6/6/1981']
* > 37
*
* Usage en dehors de Wordpress:
*
* echo chmat_age(['date' => '18/07/2016']);
*
* @param array $atts ['date' => 'jj/mm/aaaa']
*
* @return string
* @throws Exception
*/
function chmat_age($atts = []) {
$atts = array_change_key_case($atts, CASE_LOWER);
if (!array_key_exists('date', $atts) or 1 != preg_match('#^\d{1,2}/\d{1,2}/\d{4}$#', $atts['date'])) {
return '[Oups, aucune date au format jj/mm/aaaa]';
}
$dateNaissance = \DateTime::createFromFormat('d/m/Y', $atts['date']);
$now = new \DateTime();
$age = $dateNaissance->diff($now);
return $age->format('%y');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment