気をつけよう!

この記事はPHPコードを含み、開発者向けです。私たちはこのコードを好意で提供していますが、コードのカスタマイズやサードパーティの開発に関するサポートは提供していません。

さらに詳しいガイダンスについては、WPBeginnerのカスタムコードの追加に関するチュートリアルを参照してください。

解散

チェックボックスの選択肢の最小数を設定する

チェックボックスフォームフィールドの選択肢の最小数を設定したいですか?WPFormsは現在、チェックボックスフィールドの選択肢の数を制限することをサポートしています。しかし、カスタムスニペットを使用すると、小さなPHPコードスニペットを使用して、これらの選択肢の最小数を設定できるようになります。

このチュートリアルでは、チェックボックスのフォームフィールドを設定する手順を説明します。


始める前に、WPFormsがあなたのWordPressサイトにインストールされ、有効化されていることを確認し、ライセンスを確認してください。

フォームの作成

まず、新規フォームを作成するか、既存のフォームを編集してフォームビルダーにアクセスします。フォームビルダーで、フォームにチェックボックスフィールドを少なくとも1つ追加してください。

フォームを作成し、チェックボックスのフォーム・フィールドを追加します。

最小数を設定するスニペットの追加

選択肢の最小数を設定するには、以下のコード・スニペットをサイトに追加する必要があります。コード・スニペットをサイトに追加する際にサポートが必要な場合は、こちらのチュートリアルをご覧ください。

/**
 * Set minimum number of choices for a checkbox for the field
 *
 * @link https://wpforms.com/developers/how-to-set-a-minimum-number-of-choices-for-a-checkbox/
 */
 
function wpf_checkbox_validation( $field_id, $field_submit, $form_data ) {
          
    $field_submit  = (array) $field_submit;
  
    // Make sure we have an array of choices and count the number of choices.
    $count_choices = is_array( $field_submit ) ? count( $field_submit ) : 0;
  
    if ( $count_choices < 2 ) {
        wpforms()->process->errors[ $form_data[ 'id' ] ][ $field_id ] = esc_html__( 'Please select at least 2 options', 'your-text-domain' );
    }
  
}
  
add_action( 'wpforms_process_validate_checkbox', 'wpf_checkbox_validation', 10, 3 );

上のコードでは、どのチェックボックスでも最低2つの選択肢が必要です。最小数を更新したい場合は、if文の値を変更してください。

注:このスニペットは、あなたのサイトのすべてのフォームのチェックボックスフィールドに適用されます。

ユーザーがフォーム上で 2つ以下の選択肢を 選択した場合、フォーム送信時にチェックボックスフィールドの下にメッセージが表示されます。

このスニペットを使って最小限の選択肢の数を設定すると、最小限の選択肢が満たされていない場合、ユーザーにエラーが表示され、フォームは送信されません。

複数ページのフォームに制限を設定する

複数ページのフォームを使用する場合、フォームの送信を待たずにエラーを表示したい場合があります。

複数ページのフォームで「次へ」ボタンがクリックされたときに、チェックボックスフィールドの 下に警告メッセージを簡単に表示できます。

このオプションを使用するには、代わりに次のコード・スニペットをサイトに追加するだけです。

/**
 * Set minimum number of choices for a checkbox form field
 *
 * @link https://wpforms.com/developers/how-to-set-a-minimum-number-of-choices-for-a-checkbox-field/
 */
function wpf_dev_min_checkbox() {
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        var checkbox_forms = [
            /* ##### Impostare form e campi ##### */
            {form_id: 348,  min_count: 2, field_ids: [171]},
            {form_id: 348,  min_count: 3, field_ids: [173]},
            {form_id: 546,  min_count: 4, field_ids: [363]},
            {form_id: 631,  min_count: 4, field_ids: [363]},
            {form_id: 1138, min_count: 4, field_ids: [1]},
        ];

        // Live feedback on checkbox click
        $(document).on('click', '[id^=wpforms-] input[type=checkbox]', function() {
            var $form        = $(this).closest('form');
            var this_form_id = $form.data('formid');
            var $container   = $(this).closest('.wpforms-field-checkbox');
            var field_id     = $container.data('field-id');

            checkbox_forms.forEach(function(cfg) {
                if (this_form_id == cfg.form_id && cfg.field_ids.includes(field_id)) {
                    validate_checkbox_min($container, cfg.min_count);
                }
            });
        });

        // Block Next page if validation fails
        $(document).on('wpformsBeforePageChange', function(event, nextPage, $form, direction) {
            if (direction !== 'next') {
                return;
            }

            var this_form_id = $form.data('formid');
            var currentPage  = nextPage - 1;
            var is_valid     = true;

            checkbox_forms.forEach(function(cfg) {
                if (this_form_id != cfg.form_id) {
                    return;
                }

                cfg.field_ids.forEach(function(field_id) {
                    var $container = $form.find('.wpforms-field-checkbox[data-field-id="' + field_id + '"]');
                    if (!$container.length) {
                        return;
                    }

                    var field_page = $container.closest('.wpforms-page').data('page');
                    if (field_page != currentPage) {
                        return;
                    }

                    if (!validate_checkbox_min($container, cfg.min_count)) {
                        is_valid = false;
                    }
                });
            });

            if (!is_valid) {
                event.preventDefault();
            }
        });

        function validate_checkbox_min($container, min) {
            var checked  = $container.find('input[type=checkbox]:checked');
            var form_id  = $container.closest('form').data('formid');
            var field_id = $container.data('field-id');
            var warn_id  = 'wpforms-' + form_id + '-field-' + field_id + '-min-warn';

            $('#' + warn_id).remove();

            if (checked.length > 0 && checked.length < min) {
                $container.addClass('wpforms-has-error');
                $container.append(
                    '<em id="' + warn_id + '" class="wpforms-error" role="alert" aria-label="Error message">' +
                    'Si prega di spuntare tutte le ' + min + ' caselle</em>'
                );
                return false;
            }

            $container.removeClass('wpforms-has-error');
            return true;
        }

    });
    </script>
    <?php
}
add_action('wpforms_wp_footer_end', 'wpf_dev_min_checkbox');

よくある質問

以下では、チェックボックスフィールドの最小選択数の設定に関するよくある質問にお答えします。

Q: 特定のフォームと特定のフィールドIDでのみ使用できますか?

A:もちろんです!このコードを特定のフォームで使用するには、以下のコードスニペットを使用してください:

/**
 * Set minimum number of choices for a checkbox form field
 *
 * @link https://wpforms.com/developers/how-to-set-a-minimum-number-of-choices-for-a-checkbox/
 */
 
function wpf_dev_checkbox_validation( $field_id, $field_submit, $form_data ) {
     
    // Change the number to match your form ID
    if ( absint( $form_data[ 'id' ] ) !== 1289 ) {
        return;
    }
     
        $field_submit  = (array) $field_submit;
 
        // Make sure we have an array of choices and count the number of choices.
        $count_choices = is_array( $field_submit ) ? count( $field_submit ) : 0;
 
        if ( $count_choices < 2 ) {
            wpforms()->process->errors[ $form_data[ 'id' ] ][ $field_id ] = esc_html__( 'Please select at least 2 options', 'your-text-domain' );
        }
 
}
 
add_action( 'wpforms_process_validate_checkbox', 'wpf_dev_checkbox_validation', 10, 3 );

特定のフォームと特定のフィールドIDをターゲットにしたい場合は、次のコード・スニペットを使ってください。

/**
 * Set minimum number of choices for a checkbox form field
 *
 * @link https://wpforms.com/developers/how-to-set-a-minimum-number-of-choices-for-a-checkbox/
 */
 
function wpf_dev_checkbox_validation( $field_id, $field_submit, $form_data ) {
     
    // Change the number to match your form ID
    if ( absint( $form_data[ 'id' ] ) !== 1289 ) {
        return $field_id;
    }
     
    // Change this number to match the field ID
    if (absint($field_id) === 15 ) {
 
        $field_submit  = (array) $field_submit;
 
        // Make sure we have an array of choices and count the number of choices.
        $count_choices = is_array( $field_submit ) ? count( $field_submit ) : 0;
 
        if ( $count_choices < 2 ) {
            wpforms()->process->errors[ $form_data[ 'id' ] ][ $field_id ] = esc_html__( 'Please select at least 2 options', 'your-text-domain' );
        }
 
    }
 
}
 
add_action( 'wpforms_process_validate_checkbox', 'wpf_dev_checkbox_validation', 10, 3 );

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

Q: これは支払い分野にも使えますか?

A:もちろんです!支払いチェックボックス項目に使用するには、次のスニペットを使用してください。

/**
 * Set minimum number of choices for a payment checkbox form field
 *
 * @link https://wpforms.com/developers/how-to-set-a-minimum-number-of-choices-for-a-checkbox/
 */
 
function wpf_dev_limit_payment_field( $field_id, $field_submit, $form_data ) {
     
    $form_id = 731;  // Limit to form ID: Use 0 to target all forms
    $fieldID = 21;  // Limit to field ID: Use 0 to target all checkbox fields
    $min     = 2;  // Change the minimum amount
    $max     = 5;  // Change the maximum amount
 
    // Limit to specific form if {$form_id} is set
    if ( absint( $form_data[ 'id' ] ) !== $form_id && !empty( $form_id )  ) {
        return;
    }
 
    // Limit to specific field ID if {$fieldID} is set
    if ( absint( $field_id ) !== $fieldID && !empty( $fieldID ) ) {
        return;
    }
 
    // Make sure we have an array of choices and count the number of choices.           
    $count = is_array( $field_submit ) ? count( $field_submit ) : 0;
 
    // Process error if choices count is less than {$min} or greater than {$max}
    if( count( $field_submit ) < $min ) {
        wpforms()->process->errors[ $form_data[ 'id' ] ] [ $field_id ] = esc_html__( 'Please select a minimum of ' . $min .' choices.', 'your-text-domain' );
 
        } elseif ( count( $field_submit ) > $max ) {
        wpforms()->process->errors[ $form_data[ 'id' ] ] [ $field_id ] = esc_html__( 'Please select a maximum of ' . $max . ' choices.', 'your-text-domain' );
    }
 
}
add_action( 'wpforms_process_validate_payment-checkbox', 'wpf_dev_limit_payment_field', 10, 3 );

以上です!これで、チェックボックスの選択肢の最小数を設定する方法を学びました。

次に、チェックボックスの見た目をカスタマイズしたいですか?チェックボックスと複数選択フィールドをボタンのようにカスタマイズするガイドをご覧ください。

行動参照: