AIサマリー
はじめに
フォームのDate Pickerフィールドに基づいて、誰かの年齢を表示したいですか?このチュートリアルでは、生年月日(DOB)を収集し、JavaScriptを使用して計算して表示するフォームの作成方法を順を追って説明します:
- 彼らの現在の年齢
- 特定の将来(または過去)の時点における彼らの年齢
フォームの作成
新しいフォームを作り、フィールドを追加することから始めましょう。少なくとも1つのDateフィールドを含めるようにしてください。

フォームの作成にヘルプが必要な場合は、こちらのドキュメントをご覧ください。
HTMLフィールドの追加
最終的なゴールは、誕生日が選択された時点で年齢を提示することなので、そのために HTML フィールドを作る。このフィールド内に、空のHTMLスパンを埋め込みます。このスパンには "age "というクラスが割り当てられます。この空のスパンはプレースホルダーとして機能し、日付ピッカー・フィールドがユーザーの選択を捕捉すると同時に、年齢を動的に表示します。<span class="age"></span>

スニペットの追加
以下のスニペットのいずれかをサイトに追加してください。
各スニペットは特定の フォームID そして 日付フィールドID (例: 3535_9それらのIDを、ご自身のフォームとフィールドに合わせて更新してください。
オプション1:本日現在の年齢を表示する
/**
* Calculate age based on date of birth date picker field
*
* @link https://wpforms.com/developers/how-to-display-the-age-from-a-date-picker-field/
*/
function wpf_dev_check_age() {
?>
<script>
jQuery(function($) {
// Update the 3535_9 to match the form and field ID
// of your form and date picker field
window.wpforms_3535_9 = window.wpforms_3535_9 || {};
window.wpforms_3535_9.datepicker = {
mode: "single",
onClose: function(selectedDates, dateStr, instance) {
// Set today as the current date
var today = new Date();
// Set the DOB as the selected date of birth
var DOB = selectedDates[0];
// Calculate age in ms, then convert to years
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
// Build and display message
var totalMessage = 'Your age is ' + age;
jQuery('.age').text(totalMessage);
}
}
});
</script>
<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_check_age', 10 );
オプション2:選択した特定の日付における年齢を表示(将来の年齢)
特定の基準日(例:「2026年5月9日」)時点での年齢を求める場合に使用します。学校入学や資格審査など、特定の日にその人が何歳になるかを知る必要がある場合に便利です。
更新する TARGET_DATE 必要な日付に値を設定してください。
/**
* Calculate age as of a specific target date based on selected date of birth
*/
function wpf_dev_check_future_age() {
?>
<script>
jQuery(function($) {
// Update the 3535_9 to match the form and field ID
window.wpforms_3535_9 = window.wpforms_3535_9 || {};
window.wpforms_3535_9.datepicker = {
mode: "single",
onClose: function(selectedDates, dateStr, instance) {
// Fixed target date (YYYY-MM-DD)
var TARGET_DATE = new Date('2026-05-09T00:00:00');
// Selected Date of Birth
var DOB = selectedDates[0];
// If DOB is missing, do nothing
if (!DOB) {
return;
}
// Calculate age as of target date
var age = TARGET_DATE.getTime() - DOB.getTime();
// Convert ms → years
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
// Build message
var totalMessage = 'Your age on May 9, 2026 will be ' + age;
// Output into the HTML span with class "age"
jQuery('.age').text(totalMessage);
}
}
});
</script>
<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_check_future_age', 10 );
- 「目標日」は未来でも過去でも構わず、計算は成立する。
- メッセージ内に日付をハードコードしたくない場合は、以下からメッセージを構築できます:
TARGET_DATE代わりに変数。
日付ピッカー・フィールドから年齢を計算するのに必要なのはこれだけです。日付ピッカー・ポップアップの位置も変更したいですか?日付ピッカー・ポップアップの位置を変更する方法」のチュートリアルをご覧ください。
参考
アクション・リファレンス:wpforms_wp_footer