【问题标题】:Woocommerce - Validation on cart pageWoocommerce - 购物车页面上的验证
【发布时间】:2021-05-12 20:41:21
【问题描述】:

我有一个针对特定运输方式的自定义文件(见屏幕截图)。

在进行结帐之前是否有一个钩子/操作来验证此字段。当我将该字段设置为 required 时,验证将在结帐页面触发,但我希望它在 cart 页面。

验证:

//Validate the custom selection field
add_action('woocommerce_checkout_process', 'carrier_company_checkout_validation');
function carrier_company_checkout_validation() {
    Load settings and convert them in variables
    extract( custom_field_settings() );

    if(  isset( $_POST[$field_id] ) && empty( $_POST[$field_id] ) )
        wc_add_notice(
            sprintf( __("Please select a %s as it is a required field.","woocommerce"),
            '<strong>' . $label_name . '</strong>'
        ), "error" );
}

** 更新: **

就像@LoicTheAztec 在这里提到的完整代码。

一切正常。来自购物车的自定义输入值将在结账时显示,并在订单确认后保存在数据库中。但是我不知道当自定义输入为空时我必须在购物车页面上的哪个位置放置验证,因为购物车上的所有内容都在 ajax 上。

    // ##########################################
    // Add custom fields to a specific selected shipping method
    // ##########################################
    // Custom function that handle your settings
      function delivery_date_settings(){
        return array(
            'field_id'         => 'delivery_date', // Field Id
            'field_type'       => 'text', // Field type
            'field_label'      => 'label text', // Leave empty value if the first option has a text (see below).
            'label_name'       => __("Lieferdatum","woocommerce"), // for validation and as meta key for orders
        );
      }
    
    
      
      // Display the custom checkout field
      add_action( 'woocommerce_after_shipping_rate', 'carrier_company_custom_select_field', 20, 2 );
      function carrier_company_custom_select_field( $method, $index ) {
          
          if( $method->id == 'flat_rate:2' || $method->id == 'free_shipping:1') {
            extract( delivery_date_settings() ); // Load settings and convert them in variables
      
            $chosen  = WC()->session->get('chosen_shipping_methods'); // The chosen methods
            $value   = WC()->session->get($field_id);
            $value   = WC()->session->__isset($field_id) ? $value : WC()->checkout->get_value('_'.$field_id);
            $options = array(); // Initializing
        
            $chosen_method_id = WC()->session->chosen_shipping_methods[ $index ];
    
            if($chosen_method_id == 'flat_rate:2' || $method->id == 'free_shipping:1' ){                
              echo '<div class="custom-date-field">';
        
              woocommerce_form_field( $field_id, array(
                  'type'     => $field_type,
                  'label'    => $field_label, // Not required if the first option has a text.
                  'class'    => array('form-row-wide datepicker ' . $field_id . '-' . $field_type ),
                  'required' => false,
              ), $value );
      
              echo '</div>';
                  // Jquery: Enable the Datepicker
                ?>
                <script language="javascript">
                jQuery( function($){
                    $('.datepicker input').datepicker({
                        dateFormat: 'dd.mm.yy', // ISO formatting date
                    });
                });
                </script>
                <?php
            }
          }
    
    
    
    
    
      }
      
      // jQuery code (client side) - Ajax sender 
      add_action( 'wp_footer', 'carrier_company_script_js' );
      function carrier_company_script_js() {
          // Only cart & checkout pages
          if( is_cart() || ( is_checkout() && ! is_wc_endpoint_url() ) ):
      
          // Load settings and convert them in variables
          extract( lieferdatum_settings() );
      
          $js_variable = is_cart() ? 'wc_cart_params' : 'wc_checkout_params';
      
          // jQuery Ajax code
          ?>
          <script type="text/javascript">
          jQuery( function($){
              if (typeof <?php echo $js_variable; ?> === 'undefined')
                  return false;
      
              $(document.body).on( 'change', 'input#<?php echo $field_id; ?>', function(){
                  var value = $(this).val();
                  $.ajax({
                      type: 'POST',
                      url: <?php echo $js_variable; ?>.ajax_url,
                      data: {
                          'action': 'delivery_date',
                          'value': value
                      },
                      success: function (result) {
                          console.log(result); // Only for testing (to be removed)
                      }
                  });
              });
          });
          </script>
          <?php
          endif;
      }
      
      // The Wordpress Ajax PHP receiver
      add_action( 'wp_ajax_delivery_date', 'set_carrier_company_name' );
      add_action( 'wp_ajax_nopriv_delivery_date', 'set_carrier_company_name' );
      function set_carrier_company_name() {
          if ( isset($_POST['value']) ){
              // Load settings and convert them in variables
              extract( delivery_date_settings() );
      
              if( empty($_POST['value']) ) {
                  $value = 0;
                  $label = 'Empty';
              } else {
                  $value = $label = esc_attr( $_POST['value'] );
              }
      
              // Update session variable
              WC()->session->set( $field_id, $value );
      
              // Send back the data to javascript (json encoded)
              echo $label;
              die();
          }
      }
      
      
      
      // Save custom field as order meta data
      add_action( 'woocommerce_checkout_create_order', 'save_carrier_company_as_order_meta', 30, 1 );
      function save_carrier_company_as_order_meta( $order ) {
        // Load settings and convert them in variables
        extract( delivery_date_settings() );
      
        if( isset( $_POST[$field_id] ) && ! empty( $_POST[$field_id] ) ) {
            $order->update_meta_data( '_'.$field_id, esc_attr($_POST[$field_id]) );
            WC()->session->__unset( $field_id ); // remove session variable
        }
      }
      
      // Display custom field in admin order pages
      add_action( 'woocommerce_admin_order_data_after_shipping_address', 'admin_order_display_carrier_company', 30, 1 );
      function admin_order_display_carrier_company( $order ) {
          // Load settings and convert them in variables
          extract( delivery_date_settings() );
      
          $carrier = $order->get_meta( '_'.$field_id ); // Get carrier company
      
          if( ! empty($carrier) ) {
              // Display
              echo '<p><strong>' . $label_name . '</strong>: ' . $carrier . '</p>';
          }
      }
      
      // Display carrier company after shipping line everywhere (orders and emails)
      add_filter( 'woocommerce_get_order_item_totals', 'display_carrier_company_on_order_item_totals', 1000, 3 );
      function display_carrier_company_on_order_item_totals( $total_rows, $order, $tax_display ){
          // Load settings and convert them in variables
          extract( delivery_date_settings() );
      
          $carrier = $order->get_meta( '_'.$field_id ); // Get carrier company
      
          if( ! empty($carrier) ) {
              $new_total_rows = [];
      
              // Loop through order total rows
              foreach( $total_rows as $key => $values ) {
                  $new_total_rows[$key] = $values;
                  
                  // Inserting the carrier company under shipping method
                  if( $key === 'shipping' ) {
                      $new_total_rows[$field_id] = array(
                          'label' => $label_name,
                          'value' => $carrier,
                      );
                  }
              }
              return $new_total_rows;
          }
          return $total_rows;
      }

【问题讨论】:

  • @LoicTheAztec 感谢您的建议,我是 woocommerce 和 php 的新手。在这里,您可以找到购物车页面上自定义字段的完整代码。您能否看一下代码并告诉我必须在哪里为 ajax 部分添加验证?多谢!!!! gist.github.com/larzknoke/0d340bf49e3f38eaa78c88f01242b33c
  • @LoicTheAztec 好的,谢谢,问题已更新。
  • @LoicTheAztec 感谢很多,因为我对这个问题没有进一步了解......:/

标签: wordpress validation woocommerce shopping-cart woocommerce-theming


【解决方案1】:

我认为您正在寻找的钩子是 woocommerce_check_cart_items,这是在结帐之前验证购物车物品的钩子。

我不能 100% 确定您是否能够使用 $_POST 以同样的方式获得该字段,但值得一试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2019-01-31
    相关资源
    最近更新 更多