programing

Word press - 라디오 버튼 체크아웃 woocommerce 표시/숨기기 필수 필드

instargram 2023. 2. 21. 23:22
반응형

Word press - 라디오 버튼 체크아웃 woocommerce 표시/숨기기 필수 필드

저는 이탈리아 사람이고 프로그래머가 아닙니다.

저는 계산대 우커머스 사이트에 이 질문에 대답할 수 있는 두 가지 옵션이 있는 라디오 버튼을 삽입해야 합니다: "Sei un privato cittadino, un'azienda o un libero professionista?"옵션 : 1) 프리바토 치타디노 2) 아지엔다 오 리베로 프로페셔널리스타

사용자가 첫 번째 옵션을 클릭하면 필수 필드인 "codice fiscale"을 표시해야 합니다.사용자가 두 번째 옵션을 클릭하면 두 개의 필수 필드인 "P"가 표시되어야 합니다.Iva'와 Ragione sociale.폼빌링의 이 코드로 라디오 필드를 만들었습니다.php:

    <div class="woocommerce-billing-fields">
    <?php if ( wc_ship_to_billing_address_only() && WC()->cart->needs_shipping() ) : ?>

        <h3><?php _e( 'Billing &amp; Shipping', 'woocommerce' ); ?></h3>

    <?php else : ?>

        <h3><?php _e( 'Billing Details', 'woocommerce' ); ?></h3>
<?
if($key=='billing_first_name')
{
?>
<p>Sei un privato cittadino, un'azienda o un libero professionista?</p>
<input type="radio" name="choice" value="privato_cittadino">Privato cittadino
<input type="radio" name="choice" value="azienda_professionista">Azienda o libero professionista<br>
<?
}
?>
    <?php endif; ?>

올바르게 동작하지만, 지금 설명했듯이 필수 필드를 어떻게 작성해야 할지 모르겠습니다.차근차근 도와주실 수 있나요?제발, 난 프로그래머가 아니라고 생각해줘

질문에 답하려면 4단계로 진행해야 합니다.

  1. woocommerce 체크아웃 페이지에 4개의 커스텀필드를 추가합니다.이 방법은 베스트 프랙티스가 아니므로 액션/필터를 사용하여 수행해야 합니다.
  2. 백엔드에 대한 요청이 있을 때 데이터를 검증합니다.이는 사용자가 실제로 필요한 항목을 선택하고 입력했는지 확인하기 위함입니다.
  3. 나중에 액세스할 수 있도록 주문에 데이터를 포스트 메타로 저장합니다.
  4. javascript 토글 기능을 구현하여 사용자가 첫 번째 질문으로 선택한 내용에 따라 관련 필드가 표시되도록 합니다.

사용자 지정 필드를 woocommerce 체크아웃에 추가하는 중

필드를 추가할 위치에 적합한 작업을 찾아야 합니다.액션을 사용하는 것을 추천합니다.woocommerce_after_checkout_billing_form모든 개인 정보 또는 개인 정보 뒤에 필드가 표시되므로

if( !function_exists( 'custom_checkout_question_field' ) ) {
  /**
   * Add custom question field after the billing form fields
   *
   * @param Integer $order_id New order id
   */
  function custom_checkout_question_field( $checkout ) {

    echo "<div class='custom-question-field-wrapper custom-question-1'>";

    echo sprintf( '<p>%s</p>', __( "Sei un privato cittadino, un'azienda o un libero professionista?" ) );

    woocommerce_form_field( 'custom_question_field', array(
      'type'            => 'radio',
      'required'        => true,
      'class'           => array('custom-question-field', 'form-row-wide'),
      'options'         => array(
        'privato_cittadino'         => 'Privato cittadino',
        'azienda_professionista'    => 'Azienda o libero professionista',
      ),
    ), $checkout->get_value( 'custom_question_field' ) );

    woocommerce_form_field( 'custom_question_text_codice_fiscale', array(
      'type'            => 'text',
      'label'           => 'Codice Fiscale',
      'required'        => true,
      'class'           => array('custom-question-codice-fiscale-field', 'form-row-wide'),
    ), $checkout->get_value( 'custom_question_text_codice_fiscale' ) );

    woocommerce_form_field( 'custom_question_text_p_iva', array(
      'type'            => 'text',
      'label'           => 'P.Iva',
      'required'        => true,
      'class'           => array('custom-question-p-iva-field', 'form-row-wide'),
    ), $checkout->get_value( 'custom_question_text_p_iva' ) );

    woocommerce_form_field( 'custom_question_text_ragione_sociale', array(
      'type'            => 'text',
      'label'           => 'Ragione sociale',
      'required'        => true,
      'class'           => array('custom-question-ragione-sociale-field', 'form-row-wide'),
    ), $checkout->get_value( 'custom_question_text_ragione_sociale' ) );

    echo "</div>";

  }

  add_action( 'woocommerce_after_checkout_billing_form', 'custom_checkout_question_field' );
}

Javascript 프런트 엔드 토글

질문에 따라 3개의 추가 필드를 전환하려면 커스텀 Javascript를 추가해야 합니다.html을 출력하는 php 함수를 만들었습니다.scriptjavascript를 태그합니다.그런 다음 이것은 에 접속됩니다.wp_footer액션.

이 방법은 권장되지 않으므로 새 파일 js로 분리하여 필요할 때 파일을 큐에 넣어야 합니다.

참조: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts

if( !function_exists( 'custom_question_conditional_javascript' ) ) {
  function custom_question_conditional_javascript() {
    ?>
    <script type="text/javascript">
    (function() {

      // Check if jquery exists
      if(!window.jQuery) {
        return;
      };

      var $ = window.jQuery;

      $(document).ready(function() {

        var questionField       = $('.custom-question-field'),
            codiceFiscaleField  = $('.custom-question-codice-fiscale-field'),
            pIvaField           = $('.custom-question-p-iva-field'),
            ragioneSocialeField = $('.custom-question-ragione-sociale-field ');

        // Check that all fields exist
        if(
          !questionField.length ||
          !codiceFiscaleField.length ||
          !pIvaField.length ||
          !ragioneSocialeField.length
        ) {
          return;
        }

        function toggleVisibleFields() {
          var selectedAnswer = questionField.find('input:checked').val();

          if(selectedAnswer === 'privato_cittadino') {
            codiceFiscaleField.show();
            pIvaField.hide();
            ragioneSocialeField.hide();
          } else if(selectedAnswer === 'azienda_professionista') {
            codiceFiscaleField.hide();
            pIvaField.show();
            ragioneSocialeField.show();
          } else {
            codiceFiscaleField.hide();
            pIvaField.hide();
            ragioneSocialeField.hide();
          }
        }

        $(document).on('change', 'input[name=custom_question_field]', toggleVisibleFields);
        $(document).on('updated_checkout', toggleVisibleFields);

        toggleVisibleFields();

      });
    })();
    </script>
    <?php
  }

  add_action( 'wp_footer', 'custom_question_conditional_javascript', 1000 );
}

제출된 게시 요청에서 필드 가져오기

php에서 .$_POST또한 SQL 주입 또는 기타 악성 코드를 방지하기 위해 어레이를 검사합니다.에 제공된 워드프레스를 .sanitize_text_field도우미 기능

이 도우미는 포스트 메타를 검증하고 추가할 때 사용할 수 있습니다.

if( !function_exists( 'custom_checkout_question_get_field_values' ) ) {
  /**
   * Get all form field values based on user submitted post data
   *
   * @return Array Key/value pair of field values based on $_POST data
   */
  function custom_checkout_question_get_field_values() {
    $fields = [
      'custom_question_field'                       => '',
      'custom_question_text_codice_fiscale'     => '',
      'custom_question_text_p_iva'                => '',
      'custom_question_text_ragione_sociale'    => '',
    ];

    foreach( $fields as $field_name => $value ) {
      if( !empty( $_POST[ $field_name ] ) ) {
        $fields[ $field_name ] = sanitize_text_field( $_POST[ $field_name ] );
      } else {
        unset( $fields[ $field_name ] );
      }
    }

    return $fields;
  }
}

백엔드의 필드 검증

프런트 엔드는 신뢰할 수 없기 때문에 검증이 중요합니다.프런트 엔드의 필수 필드를 사용자가 쉽게 변경할 수 있습니다. Woocommerce를 할 수 .woocommerce_checkout_process필수 조건을 충족하지 못할 경우 필드를 검증하고 오류 메시지를 추가합니다.

if( !function_exists( 'custom_checkout_question_field_validate' ) ) {
  /**
   * Custom woocommerce field validation to prevent user for completing checkout
   *
   * @param Integer $order_id New order id
   */
  function custom_checkout_question_field_validate() {
    $field_values = custom_checkout_question_get_field_values();

    if ( empty( $field_values['custom_question_field'] ) ) {
      wc_add_notice( 'Please select an answer for the question.', 'error' );
    }

    if (
      $field_values['custom_question_field'] === 'privato_cittadino' &&
      empty( $field_values['custom_question_text_codice_fiscale'] )
    ) {
      wc_add_notice( 'Please enter codice fiscale.', 'error' );
    }

    if (
      $field_values['custom_question_field'] === 'azienda_professionista' &&
      empty( $field_values['custom_question_text_p_iva'] )
    ) {
      wc_add_notice( 'Please enter p iva.', 'error' );
    }

    if (
      $field_values['custom_question_field'] === 'azienda_professionista' &&
      empty( $field_values['custom_question_text_ragione_sociale'] )
    ) {
      wc_add_notice( 'Please enter ragione sociale.', 'error' );
    }

  }

  add_action( 'woocommerce_checkout_process', 'custom_checkout_question_field_validate' );
}

주문에 사용자 지정 게시 메타 저장

woocommerce를 할 수 .woocommerce_checkout_update_order_meta추가 포스트 메타를 주문 포스트 유형에 저장하기 위한 작업입니다. 기능을 사용할 예요.custom_checkout_question_get_field_valuesphp php에서 위해 되었습니다.$_POST각 파일을 포스트 메타에 저장하기 전에 배열 및 삭제하십시오.

if( !function_exists( 'custom_checkout_question_field_save' ) ) {
  /**
   * Update order post meta based on submitted form values
   *
   * @param Integer $order_id New order id
   */
  function custom_checkout_question_field_save( $order_id ) {
    $field_values = custom_checkout_question_get_field_values();

    foreach( $field_values as $field_name => $value ) {
      if( !empty( $field_values[ $field_name ] ) ) {
        update_post_meta( $order_id, $field_name, $value );
      }
    }
  }

  add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_question_field_save' );
}

언급URL : https://stackoverflow.com/questions/39336970/wordpress-radio-button-checkout-woocommerce-show-hide-required-field

반응형