Wordpress - 单选按钮结帐woocommerce显示/隐藏必填字段

时间:2016-09-05 19:59:14

标签: wordpress woocommerce field checkout radio

我是意大利人(对不起我的英语),我不是程序员。

我需要在我的结帐woocommerce网站上插入一个单选按钮,有两个选项来回答这个问题:" Sei un privato cittadino,un&#az; azienda o un libero professionista?"。 这些是选项: 1)Privato cittadino 2)Azienda o libero professionista

当用户点击第一个选项时,必须显示必填字段:" codice fiscale"。当用户点击第二个选项时,它必须显示两个必填字段:" P.Iva"和#34; Ragione sociale"。我在form-b​​illing.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; ?>

它工作正常,但现在我不知道如何创建我描述的必填字段。 你能一步一步帮助我吗?请考虑我不是程序员。

1 个答案:

答案 0 :(得分:2)

要回答该问题,将需要完成4个步骤。

  1. 将4个自定义字段添加到woocommerce结帐页面。完成此操作的方法不是最佳做法,应通过使用操作/过滤器来完成。
  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
   * @author Tameem Safi <tameem@safi.me.uk>
   */
  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前端切换

您将需要添加自定义JavaScript,以便根据问题切换其他3个字段。我创建了一个php函数,该函数将输出带有一些javascript的html script标签。然后将其附加到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注入或其他恶意代码。我创建了一个辅助函数,该函数将通过数组中提供的键来捕获所有字段,并使用wordpress 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
   * @author Tameem Safi <tameem@safi.me.uk>
   */
  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
   * @author Tameem Safi <tameem@safi.me.uk>
   */
  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_values从php $_POST数组中获取所有字段,并在将每个字段保存到post meta之前对其进行清理。

if( !function_exists( 'custom_checkout_question_field_save' ) ) {
  /**
   * Update order post meta based on submitted form values
   *
   * @param Integer $order_id New order id
   * @author Tameem Safi <tameem@safi.me.uk>
   */
  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' );
}