将自定义产品计算价格添加到 Woocommerce 购物车

时间:2023-01-17
本文介绍了将自定义产品计算价格添加到 Woocommerce 购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 woocommerce 中,我在添加到购物车按钮之前添加了一个额外的文本字段,以在产品购买时添加自定义费用.

此插件会为单个产品页面添加额外的文本字段并计算总计加上额外费用.

我的问题是我无法添加自定义购物车总数,并且在总数之前添加额外费用

我尝试了 woocommerce_cart_calculate_fees 但不幸的是它只显示 $0 的总数

PHP 代码:

/*** 检查 woocommerce 是否处于活动状态和/或已安装.*/if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) ){/*** 样式和 Ajax 脚本.*/add_action('woocommerce_single_product_summary','extra_enqueue_scripts');函数 extra_enqueue_scripts(){wp_enqueue_style('custom_style', plugins_url('/assets/css/custom_style.css', __FILE__));wp_register_script('item_add', plugins_url('/assets/js/item_add.js', __FILE__), array('jquery'), false, true );wp_enqueue_script('item_add');$array_to_be_sent = array('ajax_file_path' => admin_url('admin-ajax.php'));wp_localize_script('item_add', 'wdm_object', $array_to_be_sent);}/*** 在添加到购物车按钮之前添加文本字段.*/add_action( 'woocommerce_before_add_to_cart_button', 'extra_add_custom_field', 0 );函数 extra_add_custom_field(){$currency = get_woocommerce_currency_symbol();echo "<div class='custom-text text'><p>额外费用($currency):</p><input type='text' name='custom_price' value='' placeholder='e.g.10' title='自定义文本' class='custom_price text_custom text'></div>";}/*** 添加ajax回调函数获取数据* 并将该数据添加到会话中.*/add_action('wp_ajax_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');add_action('wp_ajax_nopriv_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');函数 extra_add_user_custom_data_options_callback(){$user_custom_data_values = (float)sanitize_text_field($_POST['custom_price']);session_start();$_SESSION['user_custom_data'] = $user_custom_data_values;死();}/*** 将数据从会话添加到购物车,然后销毁会话.*/add_filter('woocommerce_add_cart_item_data','extra_add_custom_field_data',1,2);功能 extra_add_custom_field_data($cart_item_data,$product_id){全球 $woocommerce;session_start();如果 (isset($_SESSION['user_custom_data'])){$option = $_SESSION['user_custom_data'];$new_value = array('user_custom_data_value' => $option);}如果(空($选项)){返回 $cart_item_data;}别的{如果(空($cart_item_data)){返回 $new_value;}别的{返回 array_merge($cart_item_data,$new_value);}}未设置($_SESSION['user_custom_data']);}/*** 从会话派生购物车项目.*/add_filter('woocommerce_get_cart_item_from_session', 'extra_get_cart_items_from_session', 1, 3);函数 extra_get_cart_items_from_session($item,$values,$key){如果(array_key_exists('user_custom_data_value',$values)){$item['user_custom_data_value'] = $values['user_custom_data_value'];}返回 $item;}/*** 在产品正常价格中添加额外价格.* 结帐前计算额外价格.*/add_action('woocommerce_before_calculate_totals', 'extra_price_add_custom_price');函数 extra_price_add_custom_price( $cart_object ){foreach ( $cart_object->get_cart() as $hash => $value ){if(!empty($value['user_custom_data_value']) && $value['data']->is_on_sale()){$newprice = $value['data']->get_sale_price() + $value['user_custom_data_value'];$value['data']->set_price((float)($newprice));}elseif(!empty($value['user_custom_data_value'])){$newprice = $value['data']->get_regular_price() + $value['user_custom_data_value'];$value['data']->set_price((float)($newprice));}}}/*** 在购物车表中显示额外费用.*/add_filter('woocommerce_checkout_cart_item_quantity','extra_add_user_custom_option_from_session_into_cart',1,3);add_filter('woocommerce_cart_item_price','extra_add_user_custom_option_from_session_into_cart',1,3);功能 extra_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key ){if(count($values['user_custom_data_value']) > 0){$currency = get_woocommerce_currency_symbol();$product_price = wc_get_product( $values['product_id'] );if($product_price->is_on_sale()){$price = $product_price->get_sale_price().'&nbsp;(特价!)';}别的{$price = $product_price->get_regular_price();}$custom_items = $currency.$price."<br>";$custom_items .= $currency.$values['user_custom_data_value'].'&nbsp;';$custom_items .= __("额外收费", "woocommerce");返回 $custom_items;}别的{返回 $product_name;}}/*** 如果数量为零,则删除自定义数据.*/add_action('woocommerce_before_cart_item_quantity_zero','extra_remove_user_custom_data_options_from_cart',1,1);功能 extra_remove_user_custom_data_options_from_cart($cart_item_key){全球 $woocommerce;$cart = $woocommerce->cart->get_cart();foreach( $cart as $key => $values){if ( $values['user_custom_data_value'] == $cart_item_key ){取消设置($woocommerce->cart->cart_contents[$key]);}}}/*** 结帐后添加自定义数据以订购元数据.*/add_action('woocommerce_add_order_item_meta','extra_add_values_to_order_item_meta',1,2);函数 extra_add_values_to_order_item_meta($item_id, $values){全球 $woocommerce,$wpdb;$user_custom_values = $values['user_custom_data_value'];if(!empty($user_custom_values)){$currency = get_woocommerce_currency_symbol();wc_add_order_item_meta($item_id,'额外费用',$currency.$user_custom_values);}}}别的{/*** 如果未检测到 woocommerce,则生成错误通知.*/add_action('admin_notices', 'extra_no_woocommerce');函数 extra_no_woocommerce(){$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";?><div class="错误提示"><p><?php echo sprintf("请激活或 <a href='%s' style='color:green;'>安装 Woocommerce</a> 以使用额外的字段进行产品收费插件",$err_text);?></p>

<?php}}

JS 代码

jQuery(document).ready(function(){jQuery('.single_add_to_cart_button').click(function(){jQuery.ajax({网址:wdm_object.ajax_file_path,类型:POST",数据: {动作:'add_user_custom_data_options_callback',custom_price : jQuery('.custom_price').val()},异步:假,成功:功能(数据){jQuery('.single_add_to_cart_button').text('加入购物车');}});})});

解决方案

您不需要任何 javascript 或会话来实现这一点.请尝试使用以下重新访问的代码:

//单次加入购物车前添加自定义字段add_action('woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5);函数 custom_product_price_field(){echo '

<p>额外费用('.get_woocommerce_currency_symbol().'):</p><input type="text" name="custom_price" value="" placeholder="e.g. 10" title="Custom Text" class="custom_price text_custom text">

';}//获取自定义字段值,计算新商品价格,保存为自定义购物车商品数据add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );函数 add_custom_field_data( $cart_item_data, $product_id ){if (!isset($_POST['custom_price']))返回 $cart_item_data;$custom_price = (float) sanitize_text_field( $_POST['custom_price'] );如果(空($custom_price))返回 $cart_item_data;$product = wc_get_product($product_id);//WC_Product 对象$base_price = (float) $product->get_regular_price();//产品注册价格//新的价格计算$new_price = $base_price + $custom_price;//在购物车对象中设置自定义数量$cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;$cart_item_data['custom_data']['new_price'] = (float) $new_price;$cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() );//使每个项目都是唯一的返回 $cart_item_data;}//设置新计算的购物车商品价格add_action('woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );功能 extra_price_add_custom_price( $cart ) {if ( is_admin() && !defined( 'DOING_AJAX' ) )返回;if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )返回;foreach ( $cart->get_cart() as $cart_item ) {if( isset($cart_item['custom_data']['new_price']) )$cart_item['data']->set_price( (float) $cart_item['custom_data']['new_price'] );}}//显示购物车项目自定义价格详细信息add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3);功能 display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){if( isset($cart_item['custom_data']['extra_charge']) ) {$product = $cart_item['data'];$product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );$product_price .= '
'.wc_price( $cart_item['custom_data']['extra_charge'] ).'&nbsp;';$product_price .= __("额外收费", "woocommerce");}返回 $product_price;}

代码位于活动子主题(或活动主题)的 function.php 文件中.经测试有效.

In woocommerce I have added an extra text field before add to cart button to add custom charge on product purchase.

This plugin will add extra text field to single product page and calculates total plus the extra charge.

My problem is that I cant add custom cart totals and the extra charge add before totals

I tried woocommerce_cart_calculate_fees but no luck it only show $0 in totals

PHP code:

 /**
 * Check if woocommerce is active and or installed.
 */

if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' )  )
{

/**
 * Style and Ajax script.
 */
    add_action('woocommerce_single_product_summary','extra_enqueue_scripts');

        function  extra_enqueue_scripts()
        {
            wp_enqueue_style('custom_style', plugins_url('/assets/css/custom_style.css', __FILE__));

            wp_register_script( 'item_add', plugins_url('/assets/js/item_add.js', __FILE__), array('jquery'), false, true ); 
            wp_enqueue_script('item_add'); 

            $array_to_be_sent = array( 'ajax_file_path' => admin_url('admin-ajax.php')); 

            wp_localize_script( 'item_add', 'wdm_object', $array_to_be_sent);

        }


/**
 * Add Text field Before add to cart button.
 */     

    add_action( 'woocommerce_before_add_to_cart_button', 'extra_add_custom_field', 0 );

        function extra_add_custom_field() 
        {
          $currency = get_woocommerce_currency_symbol();
          echo "<div class='custom-text text'><p>Extra Charge ($currency):</p>
          <input type='text' name='custom_price' value='' placeholder='e.g. 10' title='Custom Text' class='custom_price text_custom text'></div>";

        } 

/**
 * Add ajax callback function to get data
 * and add that data to session.
 */             

    add_action('wp_ajax_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');
    add_action('wp_ajax_nopriv_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');

        function extra_add_user_custom_data_options_callback()
        {
          $user_custom_data_values = (float)sanitize_text_field($_POST['custom_price']);
          session_start();
          $_SESSION['user_custom_data'] = $user_custom_data_values;
          die();
        }


/**
 * Add data to cart from session and then destroy session.
 */ 

    add_filter('woocommerce_add_cart_item_data','extra_add_custom_field_data',1,2);

        function extra_add_custom_field_data($cart_item_data,$product_id)
        {
            global $woocommerce;
            session_start();    
            if (isset($_SESSION['user_custom_data'])) 
            {
                $option    = $_SESSION['user_custom_data'];       
                $new_value = array('user_custom_data_value' => $option);
            }
            if(empty($option))
            {               
                return $cart_item_data;
            }
            else
            {    
                if(empty($cart_item_data))
                {
                    return $new_value;
                }
                else
                {
                    return array_merge($cart_item_data,$new_value);
                }
            }
            unset($_SESSION['user_custom_data']); 
        }


/**
 * Derive cart Item from session.
 */         

    add_filter('woocommerce_get_cart_item_from_session', 'extra_get_cart_items_from_session', 1, 3 );

        function extra_get_cart_items_from_session($item,$values,$key)
        {
            if (array_key_exists( 'user_custom_data_value', $values ) )
            {
                $item['user_custom_data_value'] = $values['user_custom_data_value'];
            }       
            return $item;
        }

/** 
 * Add extra price into product regular price.
 * Calculate extra price before checkout.
 */         

    add_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price' );

        function extra_price_add_custom_price( $cart_object ) 
        {   
          foreach ( $cart_object->get_cart() as $hash => $value )       
          { 
            if(!empty($value['user_custom_data_value']) && $value['data']->is_on_sale())
            {   
                $newprice = $value['data']->get_sale_price() + $value['user_custom_data_value'];
                $value['data']->set_price((float)( $newprice ));
            }
            elseif(!empty($value['user_custom_data_value']))
            {
                $newprice = $value['data']->get_regular_price() + $value['user_custom_data_value'];
                $value['data']->set_price((float)( $newprice ));
            }
          }
        }


/**
 * Render extra charge in cart table.
 */         

    add_filter('woocommerce_checkout_cart_item_quantity','extra_add_user_custom_option_from_session_into_cart',1,3); 
    add_filter('woocommerce_cart_item_price','extra_add_user_custom_option_from_session_into_cart',1,3);

        function extra_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
        {
            if(count($values['user_custom_data_value']) > 0)
            {
                $currency      = get_woocommerce_currency_symbol();
                $product_price = wc_get_product( $values['product_id'] );
                if($product_price->is_on_sale())
                {
                    $price = $product_price->get_sale_price().'&nbsp;(On Sale!)';
                }
                else
                {
                    $price = $product_price->get_regular_price();
                }

                $custom_items  = $currency.$price."<br>";
                $custom_items .= $currency.$values['user_custom_data_value'].'&nbsp;';
                $custom_items .= __("Extra Charge", "woocommerce" );
                return $custom_items;
            }
            else
            {
                return $product_name;
            }
        }

/**
 * Remove custom data if quantity is zero.
 */ 

    add_action('woocommerce_before_cart_item_quantity_zero','extra_remove_user_custom_data_options_from_cart',1,1);

        function extra_remove_user_custom_data_options_from_cart($cart_item_key)
        {
            global $woocommerce;
            $cart = $woocommerce->cart->get_cart();
            foreach( $cart as $key => $values)
            {
                if ( $values['user_custom_data_value'] == $cart_item_key )
                {
                    unset( $woocommerce->cart->cart_contents[ $key ] );
                }
            }
        }       



/**
 * Add custom data to order meta after checkout.
 */ 

     add_action('woocommerce_add_order_item_meta','extra_add_values_to_order_item_meta',1,2);

        function extra_add_values_to_order_item_meta($item_id, $values)
        {
            global $woocommerce,$wpdb;
            $user_custom_values = $values['user_custom_data_value'];
            if(!empty($user_custom_values))
            {
                $currency = get_woocommerce_currency_symbol();
                wc_add_order_item_meta($item_id,'Extra Charge',$currency.$user_custom_values);  
            }
        }
} 

else 

{

/**
 * Generate error notice if woocommerce is not detected.
 */ 

    add_action( 'admin_notices', 'extra_no_woocommerce' );

        function extra_no_woocommerce()
        {
            $err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
            ?>
            <div class="error notice">
            <p><?php echo sprintf("Please Activate or <a href='%s' style='color:green;'>Install Woocommerce</a> to use extra field for product charge plugin",$err_text); ?></p>
            </div>
           <?php
        }
}

JS Code

jQuery(document).ready(function(){
        jQuery('.single_add_to_cart_button').click(function(){
          jQuery.ajax({
                    url: wdm_object.ajax_file_path,
                    type: "POST",
                    data: {
                            action:'add_user_custom_data_options_callback', 
                            custom_price : jQuery('.custom_price').val()
                          },
                    async : false,
                    success: function(data){
                        jQuery('.single_add_to_cart_button').text('Added to cart');
                    }
                });
 })
 });

解决方案

You don't need any javascript or sessions to achieve that. Try the following revisited code instead:

// Add a custom field before single add to cart
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );
function custom_product_price_field(){
    echo '<div class="custom-text text">
    <p>Extra Charge ('.get_woocommerce_currency_symbol().'):</p>
    <input type="text" name="custom_price" value="" placeholder="e.g. 10" title="Custom Text" class="custom_price text_custom text">
    </div>';
}

// Get custom field value, calculate new item price, save it as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );
function add_custom_field_data( $cart_item_data, $product_id ){
    if (! isset($_POST['custom_price']))
        return $cart_item_data;

    $custom_price = (float) sanitize_text_field( $_POST['custom_price'] );
    if( empty($custom_price) )
        return $cart_item_data;

    $product    = wc_get_product($product_id); // The WC_Product Object
    $base_price = (float) $product->get_regular_price(); // Product reg price

    // New price calculation
    $new_price = $base_price + $custom_price;

    // Set the custom amount in cart object
    $cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;
    $cart_item_data['custom_data']['new_price'] = (float) $new_price;
    $cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() ); // Make each item unique

    return $cart_item_data;
}

// Set the new calculated cart item price
add_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );
function extra_price_add_custom_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if( isset($cart_item['custom_data']['new_price']) )
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['new_price'] );
    }
}

// Display cart item custom price details
add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3 );
function display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){
    if( isset($cart_item['custom_data']['extra_charge']) ) {
        $product = $cart_item['data'];
        $product_price  = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) );
        $product_price .= '<br>' . wc_price( $cart_item['custom_data']['extra_charge'] ).'&nbsp;';
        $product_price .= __("Extra Charge", "woocommerce" );
    }
    return $product_price;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于将自定义产品计算价格添加到 Woocommerce 购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:可变产品选择器:获取实时选定值 下一篇:在 Woocommerce 中重命名多个订单状态

相关文章

最新文章