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().' (On Sale!)';
}
else
{
$price = $product_price->get_regular_price();
}
$custom_items = $currency.$price."<br>";
$custom_items .= $currency.$values['user_custom_data_value'].' ';
$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');
}
});
})
});
See Question&Answers more detail:
os