The ending zeros are not showing up for the a) fee assessed and b) the total amount due columns. - parsefloat

var val = parseFloat( t.val() );
var fee = parseFloat( ( val / 100 ) * 3 ).toFixed(2));
$( '#field-convenience-fee' ).val( fee );
$( '#field-total' ).val( val + fee );
can someone help force the field-convenience-fee and total amount due fields to display the trailing zeros? (for example: 10.00 displays a fee of .3 instead of .30 and displays a total of 10.3 instead of a total of 10.30)
Plus, I have a problem with concatenation of the fee assessed + the total amount due fields.

JSFiddle for your convenience: (https://jsfiddle.net/8a2qwvsw/)
You added an extra parenthesis after toFixed(2):
var val = parseFloat( $('#t').val() );
var fee = parseFloat( ( val / 100 ) * 3 ).toFixed(2);
$( '#field-convenience-fee' ).val( fee );
$( '#field-total' ).val( val + fee );

Related

Display product cost and total price (cart + product cost) on the product page

I have the following code:
`
add_action( 'woocommerce_after_add_to_cart_form', 'total_product_and_subotal_price' );
function total_product_and_subotal_price() {
global $product;
$product_price = (float) wc_get_price_to_display( $product );
$cart_subtotal = (float) WC()->cart->subtotal + $product_price;
$price_0_html = wc_price( 0 ); // WooCommmerce formatted zero price (formatted model)
$price_html = '<span class="amount">'.number_format($product_price, 2, ',', ' ').'</span>';
$subtotal_html = '<span class="amount">'.number_format($cart_subtotal, 2, ',', ' ').'</span>';
// Display formatted product price total and cart subtotal amounts
printf('<div id="totals-section"><p class="product-total">%s</p><p class="cart-subtotal">%s</p></div>',
str_replace([' amount','0,00'], ['',$price_html], $price_0_html), // formatted html product price
str_replace([' amount','0,00'], ['',$subtotal_html], $price_0_html) // Formatted html cart subtotal
);
?>
<script>
jQuery( function($){
var productPrice = <?php echo $product_price; ?>,
startCartSubtotal = <?php echo $cart_subtotal; ?>;
function formatNumber( floatNumber ) {
return floatNumber.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ').replace('.', ',');
}
$('input[name=quantity]').on( 'input change', function(){
var productQty = $(this).val() == '' ? 1 : $(this).val(),
productTotal = parseFloat(productPrice * productQty),
cartSubtotal = productTotal + startCartSubtotal - productPrice;
cartSubtotal = $(this).val() > 1 ? parseFloat(cartSubtotal) : parseFloat(startCartSubtotal);
$('#totals-section > .product-total .amount').html( formatNumber(productTotal) );
$('#totals-section > .cart-subtotal .amount').html( formatNumber(cartSubtotal) );
});
});
</script>
<?php
}
`
This code shows me the total value of the product and the total value of the basket + the total value of the product before the product is added to the basket (they are displayed on the product page). For simple products it works correctly, for variable products it calculates me at the lowest price regardless of the price of the selected variation. How could I make the selected variation be taken into account, not the cheapest one?
I added it to functions.php, but, as I wrote in the description, it displays the minimum price, not the price of the selected variation.
Thank you very much!

Round cart total and subtotal decimals off to nearest 5 unit in WooCommerce

I have been working on the cart value roundup to the nearest value and created a function but it roundups the complete value.
What am I doing wrong?
//round cart total up to nearest dollar
add_filter( 'woocommerce_calculated_total', 'custom_calculated_total' );
function custom_calculated_total( $total ) {
$total = round( $total );
return ceil($total / 5) * 5;
}
If I have the values 44.24 I want to output as 44.25 and if I have the value as 44.28 then the output should be as 44.30
First of all you will need to use the woocommerce_cart_subtotal filter hook in addition to the woocommerce_calculated_total filter hook.
Otherwise your subtotal will deviate from the total, which seems weird
Then you can use 1 of the answers from: Rounding Mechanism to nearest 0.05
So you get:
function rnd_func( $x ) {
return round( $x * 2, 1 ) / 2;
}
function filter_woocommerce_cart_subtotal( $subtotal, $compound, $cart ) {
// Get cart subtotal
$round = rnd_func( $cart->subtotal );
// Use wc_price(), for the correct HTML output
$subtotal = wc_price( $round );
return $subtotal;
}
add_filter( 'woocommerce_cart_subtotal', 'filter_woocommerce_cart_subtotal', 10, 3 );
// Allow plugins to filter the grand total, and sum the cart totals in case of modifications.
function filter_woocommerce_calculated_total( $total, $cart ) {
return rnd_func( $total );
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );

How to adjust prices according to weight on woocommerce?

I'd like to use Woocommerce over WordPress for my shop, but clients should be able to buy the product by either unit or weight.
If X units were bought, we must measure the actual weight of the purchase (obtained during the picking and packing of the order), and adjust the price accordingly.
Is there an easy way to do this on Woocommerce?
Thanks
You can do your modification using follows code snippet -
function adjust_price_based_on_weight( $cart_object ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = $cart_item['data'];
$product_id = $cart_item['product_id'];
$quantity = $cart_item['quantity'];
$product_price = floatval( $_product->get_price() ); // Actual product price
// Do your calculation based on product quantity and weight
// for example suppose product per unit weight 2 kgs and add to cart number of unit is 3.
$product_unit_weights = $quantity * 2; // where 2kg/per unit and $quantity is 3
if( $product_unit_weights > 5 ) { // if units weights is greter than 5 kgs additional cost 10.
$additionalPrice = 10;
$_product->set_price( $product_price + $additionalPrice );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'adjust_price_based_on_weight', 99 );

Woocommerce conditional part cart discount on the same product present with > 1 variation

My woocommerce products are actually cruise expeditions (two products = two expedition types). For each product, the variations consists of the weeks in which cruises take place (= dates).
So I have Ligurian Sea Expeditions with 20 different weeks and Greece Expeditions with other 20 weeks. Fortunately I have just 2 products like that to deal with (a very simple situation)
The customer usually chooses one week expedition. However I need to apply a 10% discount on the second (or third) week in case a customer decides to apply for > 1 week. Hence the first week is paid full price, but the second and (in case there is) the third week will be discounted 10%.
I have come out with a function that enables to apply the discount in the case of two weeks.
function cart_discount() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
global $woocommerce; $cat_count = 0;
$cart = WC()->cart->get_cart();
foreach($cart as $cart_item_key => $values) {
$product_id = $values['product_id']; // product ID (= cruise type)
$variation_id = $values['variation_id']; // variation (=week)
$cart_lines_total = $values["line_total"]; //variation total price
$cart_lines_quantity = $values["quantity"];// variation quantity
//$product = 1394 = Expedition Ligurian eng
//$product = 1389 = Expedition Greece eng
//$product = 13888 = Expedition Ligurian ita
//$product = 13910 = Expedition Greece ita
//I hereby add a condition as we do have the same cruises with students prices which are not eligible to this discount (and are stored with different product_id)
if($product_id == '1394' || $product_id == '1389' || $product_id == '13888' || $product_id == '13910')
{
//put in a new array only the terms I need for the calculation later
$cart_array []= array( $product_id , $variation_id, $cart_lines_quantity, $cart_lines_total);
}
}
// discount percent is 10%
$percent = -0.10;
if ($cart_array[0][0] == $cart_array[1][0]) //if in the cart the same product is present two times
{
$discount = $percent * $cart_array[1][2] * $cart_array[1][3];
$discount_text = __( 'Quantity discount', 'woocommerce' );
WC()->cart->add_fee( $discount_text, $discount, false );
}
}
add_action( 'woocommerce_cart_calculate_fees','cart_discount' );
This code has many limitations as I said before, as it doesn't take in acccount some scenarios such as:
1) it deals only if in the cart tere are only two variations of the same product: in case a customer decides for x weeks to be purchased I should be able to check if the same product is present with > 2 variations;
2) It doesn't take into account the possibility having the two products with 2 ore more variations (ie.a person buying let's say two weeks in Ligurian Sea and two weeks in Greece)
If somebody can help me in improving the code I wrote I would be very happy!!
Just to make sure i got it right, you want to apply a discount if the customer buys more than 1 variation of the same product. Correct?
Here is the final code I wrote (it works, I have tested it)
function cart_discount() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
global $woocommerce;
$cart = WC()->cart->get_cart();
$has_coupons = count(WC()->cart->applied_coupons)>0?true:false;
if(!$has_coupons) //verifies that other discounts are not added
{
foreach($cart as $cart_item_key => $values) {
$product_id = $values['product_id']; // product ID
$variation_id = $values['variation_id']; // product quantity
$cart_lines_total = $values["line_total"];
$cart_lines_quantity = $values["quantity"];
//products for which this kind of discount must be applicable:
//$product_id = 1394 = Spedizioni CSR eng
//$product_id = 1389 = Spedizioni IDP eng
//$product_id = 13888 = Spedizioni CSR ita
//$product_id = 13910 = Spedizioni IDP ita
if($product_id == '1394' || $product_id == '1389' || $product_id == '13888' || $product_id == '13910')
{
$cart_array []= array( $product_id , $variation_id, $cart_lines_quantity, $cart_lines_total);
}
}
$conteggio = count($cart_array); //conta il numero di prodotti nel carrello
// percent is 10%
$percent = -0.10;
if ($conteggio < 3 && $cart_array[0][0] == $cart_array[1][0])
{
$discount = $percent * $cart_array[1][3];
$discount_text = __( '10% discount on subsequent week(s)', 'woocommerce' );
WC()->cart->add_fee( $discount_text, $discount, false );
}
if ($conteggio < 4 && $cart_array[0][0] == $cart_array[1][0] && $cart_array[0][0] == $cart_array[2][0])
{
$discount = ($percent * $cart_array[1][3]) + ($percent * $cart_array[2][3]);
$discount_text = __( '10% discount on subsequent week(s)', 'woocommerce' );
WC()->cart->add_fee( $discount_text, $discount, false );
}
if ($conteggio < 5 && $cart_array[0][0] == $cart_array[1][0] && $cart_array[0][0] == $cart_array[2][0] && $cart_array[0][0] == $cart_array[3][0])
{
$discount = ($percent * $cart_array[1][3]) + ($percent * $cart_array[2][3]) + ($percent * $cart_array[3][3]);
$discount_text = __( '10% discount on subsequent week(s)', 'woocommerce' );
WC()->cart->add_fee( $discount_text, $discount, false );
}
} else return;
}
add_action( 'woocommerce_cart_calculate_fees','cart_discount' );
As you see, I had to specify the product_id of the products that are interested in this particular kind of discount, which is fine for me, although it would be nicier if we could set it to categories (I didn't have the time to develop that condition)
Secondly, the part I don't like is the following
if ($conteggio < 3 && $cart_array[0][0] == $cart_array[1][0])
and all the following conditions: I was looking for a function that may go through the $cart_array and find the relations thta I set manually in each if() condition.
Thanks

Woocommerce Calculate amount by customer input in product page

In product page to get input from customer as number of words. To calculate the amount from products add-ons fixed amount to additional 10$ for each above 500 words.
ex: 1. Number of Words: 530
Normal Price + additional price: 180$ + 10$
Total: 190$
Number of Words: 1040
Normal Price + additional price: 180$ + 20$
Total: 200$
This process as to create dynamic input form customer to calculate amount the price and total amount.
`$extra_amount = (int)'10';
$amount = (int)'180'; // how to get amount from woocommerce data
if(isset($_POST['wordnumber'])){ // how to get this paramater form woocommerce post values
$test =$_POST['wordnumber'];
$original_amount = '';
if($test <= (int)'500'){
$original_amount = $amount;
}
elseif($test > (int)'500'){
$div_amount = $test/(int)'500';
$round = floor($div_amount);
//echo '<br/>';
$total_extra = $round*$extra_amount;
$original_amount = $amount+$total_extra;
}
echo $original_amount;
}`
I installed WC Fields Factory plugin then i got value from one field using key. in that i written a function and i overrided the price value.
function calculate_gift_wrap_fee( $cart_object ) {
/* Gift wrap price */
$additionalPrice = 10;
foreach ( $cart_object->cart_contents as $key => $value ) {
$test = $value['custom field'];
if( $test <= 100 ) {
$quantity = floatval( $value['quantity'] );
$orgPrice = floatval( $value['data']->price );
$value['data']->price = ( $orgPrice );
}
elseif( $test > 100 ) {
$div_amount = floatval($test/500);
$round = floor($div_amount);
$total_extra = floatval($round * $additionalPrice);
$quantity = floatval( $value['quantity'] );
$orgPrice = floatval( $value['data']->price );
$pp = ($value['price']);
$total = floatval($pp + $total_extra);
$value['data']->price = ( $orgPrice + $total );
}
}}
add_action( 'woocommerce_before_calculate_totals', calculate_gift_wrap_fee', 1, 1 );

Resources