将自定义产品计算价格添加到Woocommerce购物车 [英] Add a custom product calculated price to Woocommerce cart

查看:71
本文介绍了将自定义产品计算价格添加到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 ='eg 10'title ='Custom Text'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;
die();
}


/ **
*将数据从会话添加到购物车,然后销毁会话。
* /

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();
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);
}
}
未设置($ _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)
{
if(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()+ $值['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_custom_option_from_session_into_cart',1,3);

函数extra_add_user_custom_option_option_from_session_into_cart($ product_name,$ values,$ cart_item_key)
{
if(count($ values ['user_custom_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。= __( Extra Charge, woocommerce);
return $ custom_items;
}
其他
{
return $ 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); && lt; / p>
< / div>
<?php
}
}

JS 代码

  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,
成功:function(data){
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’< div class = custom-text text>
< p>额外费用(’.get_woocommerce_currency_symbol()。’):< / p>
< input type = text name = custom_price value =占位符=例如10 title = Custom Text class = custom_price text_custom text>
< / div>’;
}

//获取自定义字段值,计算新商品价格,将其保存为自定义购物车商品数据
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']))
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); // WC_Product对象
$ base_price =(浮动)$ product-> get_regular_price(); //产品注册价格

//新价格计算
$ new_price = $ base_price + $ custom_price;

//在购物车对象
中设置自定义金额$ cart_item_data ['custom_data'] ['extra_charge'] =(浮动)$ custom_price;
$ cart_item_data ['custom_data'] ['new_price'] =(浮动)$ new_price;
$ cart_item_data ['custom_data'] ['unique_key'] = md5(microtime()。rand()); //使每个项目都是唯一的

return $ 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()&&!define('DOING_AJAX'))
return;

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

foreach($ cart-> get_cart()as $ cart_item){
if(isset($ set_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 [ '数据'];
$ 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。= __(额外费用, 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购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆