以下の、ショートコードは、カスタムフィールド year に西暦誕生年 month に誕生月 date に誕生日 をそれぞれ入力してある場合
年齢を表示するための カスタムフィールド age に計算用のショートコード [age] を記述して、テンプレートで計算結果を受け取るものです。
functions.php
add_shortcode( 'age' , 'nobita_age' );
function nobita_age() {
global $post;
$now = date( "Ymd" );
$year = sprintf( '%04d', get_post_meta($post->ID,'year',true ) );
$month = sprintf( '%02d', get_post_meta($post->ID,'month',true ) );
$date = sprintf( '%02d', get_post_meta($post->ID,'date',true ) );
if( ! checkdate($month,$date,$year) ) {
return 'invalid date';
}
$birth = (int) $year . $month . $date;
return floor( ($now - $birth) / 10000 );
}
single.php
echo do_shortcode( get_post_meta($post->ID, 'age', true) );