【问题标题】:Create a Woocommerce product sold in units of gram创建以克为单位销售的 Woocommerce 产品
【发布时间】:2018-05-10 12:52:33
【问题描述】:

我想在 WooCommerce 中创建以克为单位销售的产品。

客户将在产品页面上输入他们想要的克数(在输入字段中),然后价格将即时计算并添加到购物车中。

我的问题是:这可能吗?如果可以,有人能给我一个“大局”的想法吗?

我不需要逐行代码,只是希望对 Woo 结构有更多了解的人可以指导我如何最好地解决问题。

我已经解决了部分问题:

  • 我可以决定为产品输入的价格是每件商品的价格 100克,所以卖家会这样输入价格。

  • 那我可以 编写一点 Javascript 来即时计算价格,然后 当用户键入他们想要的数量时,将其显示在页面上。不 问题。

但是...我认为 Woo 中的每个离散产品都需要有自己的价格。例如,如果客户想要 123 克的产品,我似乎必须在以特定的价格/金额飞行,然后将其添加到购物车。其中 (judging by this) 看起来不平凡而且有点 hacky。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: wordpress woocommerce cart product custom-fields


    【解决方案1】:

    WooCommerce 可以选择将重量显示为克。

    以下代码将在 WooCommerce 模板上将 KG 重量显示为克:

    // 转换产品重量 功能 ag_woocommerce_product_get_weight( $weight ) { // 只有当我们有一个权重时才转换 如果($重量){ // 重量以 KGS 为单位,我们希望克数乘以 1000 $重量 = $重量 * 1000; } 返回$重量; }; // 添加过滤器 add_filter('woocommerce_product_get_weight', 'ag_woocommerce_product_get_weight', 10, 1);

    希望这可能会有所帮助。干杯!

    【讨论】:

      【解决方案2】:

      WooCommerce 有一个免费插件,可让您为每个产品输入计量单位 (UOM):

      https://wordpress.org/plugins/woocommerce-unit-of-measure/

      【讨论】:

        【解决方案3】:

        我发现这个插件几乎可以满足我的需要——https://woocommerce.com/products/measurement-price-calculator/

        【讨论】:

          【解决方案4】:

          给你一个真实的例子比一步一步解释更容易、更快捷……你会看到所有步骤或任务都使用了哪些钩子。

          您不需要可变产品或即时生成变体。

          您只需为每个简单产品设置一克(或任何其他基数)的价格。现在,在这段代码中,您可以使用以下方式定位这些产品:

          • 产品 ID 数组
          • 或按产品类别(甚至产品标签)。

          您关心是关于如何传递购物车中的数据、更新每种产品的最终价格以及在购物车、结帐和订单中显示所选克数的方式。

          因此,在每个产品中,您只能按克设置价格……(或者您也可以更改代码并将产品价格设置为 100 克甚至任何其他基数)。

          代码:

          // Add a product custom field "grams_quantity" that will update the displayed price
          add_action('woocommerce_before_add_to_cart_button', 'special_product_by_grams', 25);
          function special_product_by_grams(){
              global $product;
          
              // HERE Define the special product IDs sold by grams
              $targeted_product_ids = array(37);
          
              // or HERE Define a product categories (ids, slugs or names)
              $categories = array('sold-by-gram');
          
              // Only for products sold by gram
              $product_id = $product->get_id();
              if ( ! ( in_array( $product_id, $targeted_product_ids ) || has_term( $categories, 'product_cat', $product_id ) ) ) return;
              ?>
                  <div class="grams-field">
                      <label for="grams_quantity"><?php _e('Grams: ','woocoomerce'); ?><span></span><br>
                          <input type="number" step="1" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="1">
                      </label>
                  </div><br>
          
                  <script type="text/javascript">
                      (function($){
                          // variables initialization
                          var priceByGram = <?php echo wc_get_price_to_display( $product ); ?>,
                              currencySymbol = $(".woocommerce-Price-currencySymbol").html(),
                              updatedPrice;
          
                          // On live event: imput number fields
                          $('input#grams_quantity').on( "click blur", function(){
                              updatedPrice = ($(this).val() * priceByGram).toFixed(2);
                              $(".woocommerce-Price-amount.amount").html('<span class="woocommerce-Price-amount amount">'+updatedPrice+'&nbsp;'+currencySymbol+'</span>');
                              console.log("event"); // <== To be removed
                          });
                      })(jQuery);
                  </script>
              <?php
          }
          
          // Save the "grams_quantity" custom product field data in Cart item
          add_filter( 'woocommerce_add_cart_item_data', 'save_in_cart_the_custom_product_field', 10, 2 );
          function save_in_cart_the_custom_product_field( $cart_item_data, $product_id ) {
              if( isset( $_POST['grams_quantity'] ) ) {
                  $cart_item_data[ 'grams_quantity' ] = $_POST['grams_quantity'];
          
                  // When add to cart action make an unique line item
                  $cart_item_data['unique_key'] = md5( microtime().rand() );
                  WC()->session->set( 'custom_data', $_POST['grams_quantity'] );
              }
              return $cart_item_data;
          }
          
          // Update product price by grams in cart and checkout
          add_filter( 'woocommerce_before_calculate_totals', 'update_prices_by_gram', 10, 1 );
          function update_prices_by_gram( $cart_object ) {
          
              // HERE Define the special product IDs sold by grams
              $targeted_product_ids = array(37);
          
              // or HERE Define a product categories (ids, slugs or names)
              $categories = array('sold-by-gram');
          
              foreach ( $cart_object->get_cart() as $cart_item ) {
          
                  // Only for products sold by gram
                  $product_id = $cart_item['product_id'];
                  if ( in_array( $product_id, $targeted_product_ids ) || has_term( $categories, 'product_cat', $product_id ) ){
          
                      // Get an instance of the WC_Product object and the
                      $product = $cart_item['data'];
          
                      $grams = $cart_item['grams_quantity'];
          
                      // Method is_on_sale() manage everything (dates…)
                      $product->set_price( $product->get_price() * $grams);
                  }
              }
          }
          
          // Render "grams_quantity" the custom product field in cart and checkout
          add_filter( 'woocommerce_get_item_data', 'render_product_custom_field_meta_on_cart_and_checkout', 10, 2 );
          function render_product_custom_field_meta_on_cart_and_checkout( $cart_data, $cart_item ) {
              $custom_items = array();
          
              if( !empty( $cart_data ) )
                  $custom_items = $cart_data;
          
              if( isset( $cart_item['grams_quantity'] ) )
                  $custom_items[] = array(
                      'name'      => __( 'Grams', 'woocommerce' ),
                      'value'     => sanitize_text_field( $cart_item['grams_quantity'] ),
                      'display'   => sanitize_text_field( $cart_item['grams_quantity'] ),
                  );
          
              return $custom_items;
          }
          
          // Save "grams_quantity" to the order items meta data
          add_action('woocommerce_add_order_item_meta','add_product_custom_fiel_to_order_item_meta', 1, 3 );
          function add_product_custom_fiel_to_order_item_meta( $item_id, $item_values, $item_key ) {
          
              if( isset( $item_values['grams_quantity'] ) )
                  wc_update_order_item_meta( $item_id, 'Grams', sanitize_text_field( $item_values['grams_quantity'] ) );
          }
          

          代码进入您的活动子主题(或活动主题)的 function.php 文件或任何插件文件中。

          经过测试并且有效。

          【讨论】:

          • 这很好,我很欣赏这个答案并花时间解释它。但是将 200 克产品的数量显示为 200 x 1 克会显得很奇怪......
          猜你喜欢
          • 2021-11-06
          • 1970-01-01
          • 1970-01-01
          • 2021-07-10
          • 1970-01-01
          • 1970-01-01
          • 2018-06-27
          • 1970-01-01
          • 2020-01-05
          相关资源
          最近更新 更多