• 現在、
    Year
    Month
    Day
    という数値型のカスタムフィールドがあります。
    それぞれに、生年月日の数値が入っています。

    上記三種類のカスタムフィールドを元に、年齢を自動でAgeというカスタムフィールドに値を格納する方法はありますでしょうか?

    初心者な発想で申し訳ないのですが、お力お貸しいただければ幸いです。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • モデレーター jim912

    (@jim912)

    カスタムフィールドに入れておくと、年を経るごとに更新しなければならなくなります。
    表示するだけであれば、表示する際に、生年月日の各カスタムフィールドの値から年齢を計算する方が簡単だと思いますがどうでしょう。

    こんにちは、書いてみました

    カスタムフィールド age 値 [age] を追加して、

    (計算元のフィールドは、year month date になっているので書き換えてください)

    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) );
2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「カスタムフィールド値からカスタムフィールドを作成」には新たに返信することはできません。