日付時間フィールドの日付オプションをカスタマイズする方法

WPFormsの日付時間フィールドの日付オプションをカスタマイズしたいですか?日付/時間フィールドには、日付セレクタのための2つのフォーマットオプションがあります:ユーザーにカレンダーを提供するDate Picker、またはDate Dropdownです。

バージョン1.6.3のリリースで、WPFormsはフォームビルダー内で日数制限や 過去の日付の無効化時間制限のオプションを提供します。これだけでよい場合は、こちらのドキュメントをご覧ください

このチュートリアルでは、日付ドロップダウン ・フィールドのカスタマイズと日付ピッカーの日付ブロックの計算に焦点を当てます。

このドキュメントにあるコード・スニペットのいずれかを使用する場合、フォームビルダーの日付制限オプションはオフにしておくことが重要です。日付を制限するための組み込みオプションの詳細については、こちらのドキュメントをご覧ください

フォームの作成

スニペットを追加する前に、フォームを作成してフィールドを追加する必要があります。このチュートリアルは日付ドロップダウン・フィールドに基づいているので、少なくとも1つの日付フィールドを追加する必要があります。

フォームの作成にサポートが必要な場合は、こちらのチュートリアルをご覧ください

日付フィールドを追加したら、タイプを 日付ドロップダウンに選択していることを確認してください。フォームフィールドの詳細オプションをクリックして、日付タイプを設定することができます。

日付フィールドのフォーマットを日付ドロップダウンに選択する

日付フィールドのカスタマイズ

日付フィールドをカスタマイズするには、以下のコード・スニペットのいずれかをサイトに追加する必要があります。

あなたのサイトにコード・スニペットを追加する方法を学ぶのに助けが必要な場合は、こちらのチュートリアルをご覧ください

以下のコード・スニペットの中には、特定のフォームIDとフィールドID情報を使用する必要があるものがあります。

日付ドロップダウンでスニペットを使用する

ドロップダウンの日数を月に合わせて制限する

Daysフィールドをその月の利用可能日数と一致させるには、次のスニペットを使用する。

/**
 * Limit the days dropdown to match how many days are available for the selected month.
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_days_dropdown_match_month( ) {
?>
  
<script type="text/javascript">
    var date = new Date();
 
    var month = date.getMonth();
 
    var year = date.getFullYear();
 
    var totalDays = 31; // Default day amount
 
    jQuery(function($){
 
        $( 'select[id$="-month"]' ).on( 'change', function(){
            month = $(this).val();
            totalDays = daysInMonth(month, year);
            $(this).parent().find( 'select[id$="-day"] option:not(:first-child)').each(function(){
                $(this).remove();
            });
            for (var i = 1; i <= totalDays; i++) {
                $(this).parent().find( 'select[id$="-day"]' ).append($( "<option></option>" ).attr( "value", i).text(i));
            }
        });
 
        $( 'select[id$="-year"]' ).on( 'change', function(){
            year = $(this).val();
            totalDays = daysInMonth(month, year);
            $(this).parent().find( 'select[id$="-day"] option:not(:first-child)').each(function(){
                $(this).remove();
            });
            for (var i = 1; i <= totalDays; i++) {
                $(this).parent().find('select[id$="-day"]').append($( "<option></option>" ).attr( "value", i).text(i));
            }
        });
    });
     
    function daysInMonth (month, year) {
        return new Date(year, month, 0).getDate();
    }
    </script>
  
<?php
}
  
add_action( 'wpforms_wp_footer_end', 'wpf_dev_days_dropdown_match_month', 30 );

日付のドロップダウンで月、日、年を制限する

以下のスニペットは、利用可能な月が5-12(5月-12月)利用可能な日が20-31利用可能な年が2020-2021のみ表示されるようにドロップダウンフィールドを更新します。必要に応じてフィールドを変更することができます。

この適用には2つの異なる方法がある:

  • 特定のフォーム内のすべての日付ドロップダウンフィールド
  • 特定のフォーム内の特定の日付のドロップダウン。

特定のフォーム内のすべての日付ドロップダウンフィールド

以下のスニペットは、フォームID10にのみ適用されます。

/**
 * Filters labels and options within the date field’s dropdown format.
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_datetime_date_dropdowns( $args, $form_id, $field ) {
 
    $form_id = (int) $form_id;
 
    // Only apply if the form's ID is 10
    if ( $form_id === 10 ) {
 
        // Set the lower and upper limits for each date dropdown
        $args[ 'months' ] = range( 5, 12 ); 
        $args[ 'days' ] = range( 20, 31 ); 
        $args[ 'years' ] = range( 2024, 2025 ); 
 
    }
 
    return $args;
}
add_filter( 'wpforms_datetime_date_dropdowns', 'wpf_dev_datetime_date_dropdowns', 10, 3 );

特定のフォーム内の特定の日付のドロップダウンをターゲットにする

以下は、フォームID10内のフィールドID3の日付ドロップダウンに適用されます。

/**
 * Filters labels and options within the date field’s dropdown format.
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_datetime_date_dropdowns( $args, $form_id, $field ) {
 
    $form_id = (int) $form_id;
     
    // Only apply if the form's ID is 10 and field ID 3
    if ( $form_id === 10 && $field['id'] == 3) {
 
        // Set the lower and upper limits for each date dropdown
        $args[ 'months' ] = range( 5, 12 ); 
        $args[ 'days' ] = range( 20, 31 ); 
        $args[ 'years' ] = range( 2024, 2025 ); 
 
    }
 
    return $args;
}
add_filter( 'wpforms_datetime_date_dropdowns', 'wpf_dev_datetime_date_dropdowns', 10, 3 );

日付のドロップダウンを「今日」から開始

日付ドロップダウンでは、このスニペットを使って、年を自動的に今日の月、日、年で始まるようにデフォルト設定することができます。

/**
 * Select from today's date going forward within the range limit specified below
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_datetime_date_dropdowns( $args, $form_id, $field ) {
     
    if( $form_id != 143 ) {
        return $args;
    }
 
    // Set the lower and upper limits for each date dropdown
 
    $args[ 'months' ] = range( date('m'), 12 ); 
    $args[ 'days' ] = range( date('d'), 31 ); 
    $args[ 'years' ] = range( date('Y'), 2030 );
     
    return $args;
}
add_filter( 'wpforms_datetime_date_dropdowns', 'wpf_dev_datetime_date_dropdowns', 10, 3 );

日付ピッカーでスニペットを使う

過去の日付を無効にし、次の31日間のみを表示する

このスニペットでは、過去の日付を無効にし、現在の日付から31日以内のフォームIDのみを選択できるようにします。 1137 とフィールドID 14.これらのIDを、あなた自身のフォームとフィールドのIDに合わせて変更することを忘れないでください。これらのIDがどこにあるかわからない場合は、次のようにしてください、 このチュートリアルをお読みください.

/**
 * Disable past dates, allow for selection for today + the next 31 days
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
  
function wpf_limit_date_picker() {
    ?>
    <script type="text/javascript">
    var d = new Date();
        window.wpforms_1137_14 = window.wpforms_1137_14 || {};
            window.wpforms_1137_14.datepicker = {
            disableMobile: true,
            // Don't allow users to pick dates less than 1 days out
            minDate: d.setDate(d.getDate()),
            maxDate: d.setDate(d.getDate() + 31),
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_limit_date_picker', 10 );

昨日、今日、明日の日付を表示する

new Date().fp_incr(-1)を使えば、数値を増やすだけで、minDateと maxDateの表示日数を簡単にコントロールできる。数値の前に負の記号(-)を使うと、過去の日数になります。

フォームを昨日から開始したいので、minDateは (-1)のみで開始し、maxDateは (1)で終了する(つまり今日と明日を含む)。

/**
 * Allow date picker yesterday, today, and tomorrow
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
  
function wpf_dev_limit_date_picker() {
    ?>
    <script type="text/javascript">
        window.wpforms_datepicker = {
            disableMobile: true,
            // Don't allow users to pick past dates
            minDate: new Date().fp_incr(-1), // 1 day in the past
            // Don't allow users to pick any more than today
            maxDate: new Date().fp_incr(1) // 1 day in the future
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker', 10 );

日付ピッカーに翌日以降の日付を表示する

このコード・スニペットを使えば、過去の日(今日を含む)を除外することが簡単にできる。

単に +1)を変更し、何日先までピッカーを制限したいかを指定します。

/**
 * Show dates from the next day and onwards
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_limit_date_picker() {
    ?>
    <script type="text/javascript">
        var d = new Date();
        window.wpforms_datepicker = {
            disableMobile: true,
            // Don't allow users to pick dates less than 1 days out
            minDate: d.setDate(d.getDate() + 1),
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_limit_date_picker', 10 );

日付ピッカーで特定の日付範囲をブロックする

日付ピッカー内で特定の日付範囲をブロックするには、次のスニペットを使用します。

/**
 * Limit the dates available in the Date Time date picker: Block out certain date ranges
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_limit_date_picker() {
    ?>
    <script type="text/javascript">
        var d = new Date();
        window.wpforms_datepicker = {
            disableMobile: true,
            // Don't allow users to pick specific range of dates
            disable: [
                {
                    from: "2024-12-24",
                    to: "2024-12-26"
                },
                {
                    from: "2024-12-31",
                    to: "2025-01-01"
                }
            ]
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_limit_date_picker', 10 );

ユーザーが日付ピッカー内で日付を選択できる範囲を制限する。

ユーザーが日付ピッカー内で選択できる未来の日付を制限したい場合は、次のコード・スニペットを使用してください。

/**
 * Don't allow date to be selected after maxDate
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_limit_date_picker() {
    ?>
    <script type="text/javascript">
        window.wpforms_datepicker = {
            disableMobile: true,
            // Don't allow users to pick past dates
            minDate: new Date(),
            // Don't allow users to pick dates after Dec 31, 2025
            maxDate: new Date( '2025-12-31' )
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker', 10 );

日付ピッカーで過去のすべての日と月曜日を除外する。

過去のすべての日と将来の月曜日を制限するには、次のスニペットを使用します。

/**
 * Don't allow users to pick Mondays
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_limit_date_picker() {
    ?>
    <script type="text/javascript">
        window.wpforms_datepicker = {
            disableMobile: true,
            // Don't allow users to pick past dates
            minDate: new Date(),
            // Don't allow users to pick Mondays
            enable: [
                function(dateObj){
                    return dateObj.getDay() !== 1;
                }
            ]
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker', 10 );

現在の日付を選択したときのメッセージ表示

この例では、現在の日付が選択されたときにポップアップ・メッセージを表示する。

/**
 * Display pop up message when current date is selected
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
 function wpf_dev_check_date() {
    ?>
    <script type="text/javascript">
// Only display the message if the form ID is 323 and the field ID is 4
            window.wpforms_323_4 = window.wpforms_323_4 || {};
            window.wpforms_323_4.datepicker = {
                mode: "single",
                onClose: function(selectedDates, dateStr, instance) {
                    var today = new Date(); 
                    if (selectedDates[0].toLocaleDateString("en-US") == today.toLocaleDateString("en-US")) {
                        alert( 'Custom Message: You have selected todays date' );
                        this.clear();
                    }
       
                }
       
            }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_check_date', 10 );

特定の曜日を無効にする

この例では、次のスニペットを使って、日付ピッカーから日曜日を完全に無効にしたい。

/**
 * Disable a specific day of the week
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_limit_date_picker_disable_specific_weekday() {
    ?>
    <script type="text/javascript">
        var d = new Date();
 
        // Only apply to the form ID 420 and the field ID 1
        window.wpforms_420_1 = window.wpforms_420_1 || {};
        window.wpforms_420_1.datepicker = {
            disableMobile: true,
            // Don't allow users to pick specific day of the week
            disable: [
                function(date) {
                    // return true to disable
                    // 1 = Monday; 2 = Tuesday; 3 = Wednesday; 4 = Thursday; 5 = Friday; 6 = Saturday; 0 = Sunday
                    return (date.getDay() === 0);
                }
            ]
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_limit_date_picker_disable_specific_weekday', 10 );

このスニペットでは、(date.getDay() === 0); を返すと、日曜日だけが無効になる。各日は特定の数字で表されます。

  • 1 = 月曜日
  • 2 = 火曜日
  • 3 = 水曜日
  • 4 = 木曜日
  • 5 = 金曜日
  • 6 = 土曜日
  • 7 = 日曜日

特定の日の数値表現を見つけ、希望の日に合わせてスニペットを更新するだけだ。

window.wpforms_420_1はフォームID(420)と日付ピッカーのフィールドID(_1)を表しています。この2つのIDを、あなた自身のフォームIDとフィールドIDに合わせて更新する必要があります。

フォームとフィールドのID番号の見つけ方については、こちらのチュートリアルをご覧ください

カレンダーの開始日を変更する

日付ピッカーの曜日を週の始まりに変更するには、このスニペットを使います。月曜日は 数字の1を表し、曜日は数字順に続くことを覚えておいてください。

/**
 * Change the start day of the week
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_set_start_day() {
    ?>
    <script type="text/javascript">
        window.wpforms_datepicker = {
            disableMobile: true,
            "locale": {
                 
        // Enter the number for the day you want the week to start
        // 1 = Monday; 2 = Tuesday; 3 = Wednesday; 4 = Thursday; 5 = Friday; 6 = Saturday; 7 = Sunday
                 
                "firstDayOfWeek": 1 // start week on Monday
            }
        }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_set_start_day', 10 );

未来の日付を無効にする

このスニペットを使用すると、maxDateが今日の日付(現在)に設定されるため、ユーザーは将来の日付を選択できなくなります。

/** 
* Disable future dates 
* 
* @link https://wpforms.com/developers/customize-the-date-time-field-date-options/ 
*/
function wpf_dev_limit_date_picker() { 
   ?> 
   <script type="text/javascript"> 
      window.wpforms_datepicker = { 
        disableMobile: true, 
        // Don't allow users to pick past dates 
        maxDate: new Date(), 
      } 
   </script> 
  
   <?php 
} 
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker', 10 );

日付ピッカー内の特定のフォームIDとフィールドIDをターゲットにする

日付ピッカーを使用する場合、単一のフォームまたは特定のフォーム内の特定の日付フィールドをターゲットにすることができます。

以下のスニペットの例では、window.wpforms_21_1.21はフォームID、_1はフィールドIDを表します。

フォームとフィールドのID番号を見つけるのに助けが必要な場合は、こちらのチュートリアルをご覧ください

ここにいくつかのコード・スニペットがあります。最初のものは、過去30日間のみを選択できるようにするものです:

/**
 * Only allow for a selection of only the past 30 days
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_limit_date_picker() {
    ?>
    <script type="text/javascript">
        window.wpforms_21_1 = window.wpforms_21_1 || {};
        window.wpforms_21_1.datepicker = {
            disableMobile: true,
            // Don't allow users to pick more than 30 days in the past and exclude future dates
            minDate: new Date().fp_incr(-30)
            }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker', 10 );

次のコード・スニペットでは、過去30日間と "今日 "を選択できるようにする:

/**
 * Only allow for a selection of the past 30 days and "today"
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_limit_date_picker() {
    ?>
    <script type="text/javascript">
        window.wpforms_21_1 = window.wpforms_21_1 || {};
        window.wpforms_21_1.datepicker = {
            disableMobile: true,
            // Don't allow users to pick more than 30 days in the past
            minDate: new Date().fp_incr(-30),
        maxDate: "today"
            }
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker', 10 );

当月のみ1日に限定

この例では、当月の1日のみの予約を受け付けることにします。

/**
 * Limit to 1 single day for the current month only.
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
  
function wpf_dev_one_day_current_month( ) {
?>
   
<script type="text/javascript">
        window.wpforms_datepicker = {
            disableMobile: true,
            disable: [
                function(date) {
                    var currentDate = new Date();
                    var currentMonth = currentDate.getMonth();
                    var currentYear = currentDate.getFullYear();
                    var selectedMonth = date.getMonth();
                    var selectedYear = date.getFullYear();
 
                    if (selectedMonth !== currentMonth || selectedYear !== currentYear) {
                        return false;
                    }
 
                    var day = date.getDay();
                    var firstDayOfMonth = new Date(selectedYear, selectedMonth, 1).getDay();
                    var offset = (day >= firstDayOfMonth) ? (day - firstDayOfMonth) : (day + 7 - firstDayOfMonth);
                    var secondThursday = new Date(selectedYear, selectedMonth, offset + 8);
 
                    if (date.getDate() === secondThursday.getDate() && day === 4) {
                        return false;
                    }
 
                    return true;
                }
            ]
        };
    </script>
   
<?php
}
   
add_action( 'wpforms_wp_footer_end', 'wpf_dev_one_day_current_month', 30 );

この例では、2つ目の日付選択フィールドの最小日付を動的に設定し、最初に選択した日付から少なくとも21日後であることを保証しています。

/**
 * Add 21 days to the first date selection to block these days from the second selection
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options/
 */
 
function wpf_dev_block_days_date_selection( ) {
?>
  
<script type="text/javascript">
        jQuery(document).ready(function($) {
             
            $( "#wpforms-1277-field_19" ).flatpickr({
                dateFormat: "m/d/Y",
                onClose: function( selectedDates, dateStr, instance ) {
                    if ( selectedDates.length > 0 ) {
                        var minSecondDate = new Date( selectedDates[0] );
                        // Adding 21 days to the selected 1st date
                        minSecondDate.setDate( minSecondDate.getDate() + 21 ); 
                        $( "#wpforms-1277-field_20" ).flatpickr({
                            minDate: minSecondDate,
                            dateFormat: "m/d/Y"
                        });
                    }
                }
            });
        });
    </script>
  
<?php
}
  
add_action( 'wpforms_wp_footer_end', 'wpf_dev_block_days_date_selection', 30 );

日付と時刻のサブラベルの翻訳

Date/Timeフィールドの "Date "と "Time "サブラベルを翻訳するには、次のコード・スニペットを使うことができる:

``/**
 * Translate Date and Time sublabels in the Date/Time field
 *
 * @link https://wpforms.com/developers/customize-the-date-time-field-date-options
 */
function custom_translate_date_time_sublabels( $properties, $field, $form_data ) {
    // Check if the field is of type 'date-time'
    if ( 'date-time' === $field['type'] ) {
        // Change the sublabel for the date field
        if ( isset( $properties['inputs']['date']['sublabel']['value'] ) ) {
            $properties['inputs']['date']['sublabel']['value'] = __( 'Your Translated Date Label');
        }
        // Change the sublabel for the time field
        if ( isset( $properties['inputs']['time']['sublabel']['value'] ) ) {
            $properties['inputs']['time']['sublabel']['value'] = __( 'Your Translated Time Label');
        }
    }
    return $properties;
}
add_filter( 'wpforms_field_properties', 'custom_translate_date_time_sublabels', 10, 3 );

このスニペットを使うには

  1. あなたの翻訳した日付ラベル」を、「日付」の希望する翻訳に置き換える。
  2. Your Translated Time Label'を "Time "の訳に置き換えてください。

例えば、ラベルをスペイン語に翻訳する:

$properties['inputs']['date']['sublabel']['value'] = __( 'Fecha');
$properties['inputs']['time']['sublabel']['value'] = __( 'Tiempo');

最後に、このドキュメントにあるコードスニペットを使用する場合、フォームビルダーの日付制限オプションはオフにしてください。日付を制限するための組み込みオプションの詳細については、こちらのドキュメントをご覧ください

日付ドロップダウンまたは日付ピッカーをカスタマイズするのに必要なのはこれだけです!日付ピッカーをカスタマイズして、日付の範囲や複数の日付を指定できるようにしたいですか?チュートリアル「日付ピッカーで日付範囲または複数の日付を許可する方法」をお試しください。

リファレンス・フィルターとアクション

wpforms_datetime_date_dropdowns

wpforms_wp_footer_end