创建以克为单位销售的 Woocommerce 产品

Create a Woocommerce product sold in units of gram

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

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

我的问题是:这是否可能,如果可能,有人可以给我一个 "big picture" 我将如何实施它的想法吗?

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

我已经解决了部分问题:

但是...我认为 Woo 中的每个离散产品都需要有自己的价格。例如,如果客户想要 123 克的产品,我似乎必须创建一个变体 为特定 price/amount 即时 ,然后将其添加到购物车。其中 (judging by this) 看起来很重要,而且有点老套。有更好的方法吗?

WooCommerce 有一个选项可以将重量显示为克。

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



    // Convert the product weight
       function ag_woocommerce_product_get_weight( $weight ) {

       // Only convert if we have a weight
    if ($weight) {

    // The weight is in KGS, and we want grams, to multiple by 1000
    $weight = $weight * 1000;
    }

    return $weight;
    };
    // add the filter
    add_filter( 'woocommerce_product_get_weight', 'ag_woocommerce_product_get_weight', 10, 1 );

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

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

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

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

  • 一组产品 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 文件或任何插件文件。

已测试并有效。

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

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

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