Woocommerce: How-to show ‘Order Total’ amount in Words - wordpress

On my Woocommerce website, I need to display Total Order Amount in words, which will be shown on Checkout Page, Cheque Payment & on Invoice.
Example: 1590.00 (One thousand five hundred & ninety only)
How can we achieve this?
TIA

You can try number formatter class as mentioned in these threads a and b
Use the filter "woocommerce_cart_totals_order_total_html".
function custom_woocommerce_order_amount_total( $order_total ) {
$number_total = WC()->cart->get_total();
// number formatting goes here;
// using number formatter class
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
$total_in_words = $f->format($number_total); // Total in words
$order_total = $total_in_words;
return $order_total;
};
add_filter( 'woocommerce_cart_totals_order_total_html', 'custom_woocommerce_order_amount_total' );
You can also try the other hooks like woocommerce_get_formatted_order_total

Related

Gravity forms conditional logic based on number of values selected

I have a form built with gravity forms that asks 5 questions, each with 2 answers.
Each answer corresponds to a category, and so I want to be able to add some conditional logic so that the confirmation sends to a different page depending on which category has more answers.
Form is here: https://90daysfromretirement.com/medicare-advantage-vs-medicare-supplement/
The two categories are "Advantage" and "Supplement" - so dependng on the answer, so whichever category has more responses (3 or greater) then the confirmation will redirect them to the appropriate page.
Problem is I can't figure out how to Count the values for each and run logic off it. I don't think it's possible with any gravity forms add-ons I've found, and I haven't been able to put the code together to do it.
Any suggestions?
Since you only have two options, you really only need to know the count of one and the total number of questions to know which value has been selected more.
For example, if you have 10 questions and "Advantage" choices are selected 6 times, you know that Advantage has more than "Supplement".
Here's a snippet that should get you started. It will take a group of Radio Button fields, count the number of times a specified value has been selected, and populate that count into a Number field.
You can then use that Number field to apply conditional logic on your confirmations to redirect to the appropriate page (e.g. If Count is greater than 5, redirect to Advantage page. If Count is less than 6, redirect to Supplement page).
/**
* Gravity Wiz // Gravity Forms // Value Counter
* https://gravitywiz.com/
*
* Count the number of times a given value has been selected in a group of fields and populate that number into a Number field.
* This snippet is designed to target a Number field and count selected values in Checkbox and Radio Button fields.
*
* This snippet works best with our free [GF Custom Javascript](https://gravitywiz.com/gravity-forms-custom-javascript/) plugin.
*/
// Replace the "1", "2" and "3" with field IDs of fields that should have their selected values counted. If you are using the
var $radios = jQuery( '#field_GFFORMID_1, #field_GFFORMID_2, #field_GFFORMID_3' );
// Replace "4" with the ID of the Number field in which the count should be populated.
var $target = jQuery( '#field_GFFORMID_4' );
// Replace "a" with the value you wish to count if selected.
var countValue = 'a';
function gwRecountValues() {
$target.find( 'input' ).val( $radios.find( 'input:checked[value="' + countValue + '"]' ).length );
}
$radios.on( 'change', function() {
gwRecountValues();
} );
gwRecountValues();
And here's the source which may be updated in the future if other folks use this and experience any issues or need improvements: https://github.com/gravitywiz/snippet-library/commit/d34eb169da937981c4a1ea49bb8a36df023bff1b
The one thing missing from this snippet is PHP validation. You may not be concerned about people altering their count but it is possible without PHP validation.
You could try adding the following to your functions.php file
add_action( "gform_after_submission_66", "after_submission", 10, 2 ); //replace 66 with your form number
function after_submission($entry, $form ){
$supplement_answers = array("milk", "apple", "pasta", "fries", "oats"); //replace array items with the supplement answers
$advantage_answers = array("red", "blue", "pink", "purple", "yellow"); //replace array items with the advantage answers
$field_nums = array("2","3","6","7","9"); //replace these field numbers with your own -- order then to align with answers above
$count_fields = count($field_nums);
$a = 0;
$b = 0;
for($i=0; $i<$count_fields; $i++){
if($entry[$field_nums[$i]] == $supplement_answers[$i]){
$a = $a + 1;
}else if($entry[$field_nums[$i]] == $advantage_answers[$i]){
$b = $b + 1;
}
}
if($a > $b){
header('Location: https://website/supplements_page'); //replace url
}else if($a < $b){
header('https://website/advantage_page'); //replace url -
}
}

Woocommerce discount - percentage only in whole numbers sent to distribution - how to calculate without losses for the customer or company

I am trying to figure out how to control the discount behavior of my website so it collaborates with an external distribution channel. Right now i have a successful mail send with a XML-file attached when the customer has finished paying.
The only data field that is causing trouble is the discount. Because:
The disctribution channel only accepts discount for each item (product) as percentage that is a whole number
I've used simpleXML and added data for each item (sold product) like this - only a section of the full code
// Basic $order data and wp_mail configurations BEFORE
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$isbn = get_field( 'isbn', $item->get_product_id() );
$price = $product->get_price();
$quantity = $item->get_quantity();
$order_line = $order_head->addChild( 'Ordrelinje' );
$order_line->addAttribute( 'besked', 'notat tilknyttet ordrelinjen' );
$order_line->addAttribute( 'rabatprocent', '' );
$order_line->addAttribute( 'stykpris', $price );
$order_line->addAttribute( 'antal', $quantity );
$order_line->addAttribute( 'isbn', $isbn );
}
// SimpleXML save and attachment created with the XML file AFTER
// Sent with wp_mail and the return tested AFTER
So the problem is basically:
I know how to calculate the percentage from full price and discount in the product[] data, but i have difficulties imagine a flexible system with different discount-possibilities (see bottom)
With both percentage- and amount discount you could imagine having a conflict with whole based number when calculating the percentage after purchase. Some decimals would be lost.
Example:
Let's say that i make a discount on one book at 22 KR (danish) and the price without discount were: 143.
Then the discount in percentage would be: 100/143*22: 15.38%.
I would then for example, to get a whole number as percentage, round with round(15.38, 0) to get 15.
And then the customer would lose: .38% that is 143*0.0038 = 0.54KR
So my question is:
Does anyone has an idea how to get solve this, or a workaround so the amount discount is a whole number of the regular price in percentage for example. Or have other ideas?

How to get total number of rows in a drupal view alter hook?

I've to avoid duplicate search result in a view, so what I am trying to alter the view using pre render hook. and removing the duplicates it's working fine but the problem is in the count of result. it shows the count from the query executed and this include the duplicated item too. also, I enabled the pagination with limit of 5 in a page. then the count seems to be strange it's taking the count of the elements showing in each page
function search_helper_views_pre_render(\Drupal\views\ViewExecutable $view) {
if ($view->id() == "all_news" || $view->id() == "all_publications" || $view->id() == "all_events" || $view->id() == "global_search") {
$unique_nids = $d_nids = $new_results = array();
// Loop through results and filter out duplicate results.
foreach($view->result as $key => $result) {
if(!in_array($result->nid, $unique_nids)) {
$unique_nids[] = $result->nid;
}
else {
unset($view->result[$key]);
}
}
$view->total_rows = count($view->result);
//$view->pager->total_items = count($view->result);
$view->pager->updatePageInfo();
}
}
the expected output of the $view->total_rows must be the total count of result instead of count of elements shown in the page.
You totaly done it in wrong way. as you see ( and it's clear from its name ), it's hook__views_pre_render it runs before the rendering. So its really hard to manipulate the views results and counter, pagination there.
As I see in your query you just remove duplicate Nids , so you can easily do it by Distinct drupal views feature.
Under Advanced, query settings, click on settings.
You will get this popup, now checkmark Distinct
Could do
$difference = count($view->result) - count($new_result);
$view->total_rows = $view->total_rows - $difference;
BTW Distinct setting doesn't always work, see https://www.drupal.org/project/drupal/issues/2993688

Adobe Catalyst - 'Attribute Price' adding on to 'Sell Price' Issue

I have set a products sell price at £100. I have also created a 'Size' attribute at 'Large' £120.
But when I view the product and select 'Large' it prices up at £220 (adding the attribute and sell price together) when I'm wanting it at just the £120.
Any thoughts on why I'm getting this issue?
I believe Daut maybe talking about something else but I could be wrong.
When using attributes that you talk about, the price is calculated by default price plus the attribute price. This is why you see £220 as your total, as you have figured out.
In other words, your default price is £100. For your total to be £120, then your Large attribute would actually be £20. When it adds together, your total price will be £120.
When I use attributes with varying cost, I typically write my attribute as:
Large + [then BC inserts the price.]
On the BC App Store, there are a couple plugins (here and here) that assist with using Attributes. Their main purpose, from my understanding, is controling how the information is displayed to customers. I have no experience using either of these but it may help you.
Hi have created my own way around this issue in BC I also shared it on Business Catalyst Forum too. for select dropdown or radio buttons use the code bellow, you need to have a certain code ability to mend it together, it was quite done some time ago but if somebody interested on improving it to a cleaner way be welcome to share.
$(document).ready(function(){
StartDynamicPrice();
DoPriceChange();
});
var el_totalprice='#totalprice';
var el_totalprice_gst='#totalprice_gst';
//var el_attrselect='.catProdAttributeItem select';
// uncomment if you want radio as well
var el_attrselect='.catProdAttributeItem select, .catProdAttributeItem input';
var currencysymbol='£';
Number.prototype.toMoney=function(decimals, decimal_sep, thousands_sep){
var n = this,
c = isNaN(decimals) ? 2 : Math.abs(decimals),
d = decimal_sep || '.',
t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
sign = (n < 0) ? '-' : '',
i = parseInt(n = Math.abs(n).toFixed(c)) + '',
j = ((j = i.length) > 3) ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}
DoPriceChange=function(){
var selected='';
var newsubtotal=0;
$.each($(el_attrselect), function(i,e){
selected=$(e).children(':selected').text();
if (selected.indexOf(currencysymbol) != -1){
newsubtotal+=parseFloat(selected.substring(selected.indexOf(currencysymbol)+1));
};
});
newtotal=parseFloat($(el_totalprice).attr('base'))+parseFloat(newsubtotal);
newtotal_gst=newtotal+(newtotal*.10);
$(el_totalprice).html(currencysymbol+newtotal.toMoney());
$(el_totalprice_gst).html(currencysymbol+newtotal_gst.toMoney());
}
StartDynamicPrice=function(){
$(el_totalprice).attr('base',$(el_totalprice).html().replace(currencysymbol,'').replace(' ,','')); // set base price
$(el_attrselect).on('change',function(){
DoPriceChange();
})
}
/// END
Attributes in BC are add-ons. You cannot just get the attribute.
What you need is product grouping.
Group products together
You can create multiple products of the same type and group them together. A customer viewing one product can also see the available variations by selecting another product from the group.
Check how Grouping works in Business Catalyst
From the Actions menu, select Group Products Together.
Move the products from the left panel to the right, select a default product, and click Save.
Note: The default product is the only product that displays in a catalog. All other grouped products are available through the grouped product drop-down menu.

Apply logical Pricing on Woocommerce Attributes

Dear I've a Pizza site and I'm using Woocommerce plugin. I want to apply some price check on attributes.
My Question is
I've a Pizza product which attributes are Size and Meat. Size(Small,large) Meat(Chicken, donair meat etc).
I've applied a check on attributes that when a customer select a product size, small and one piece of meat, the price will be $10 on default rate. But I want to apply this logic here that, when a customer select a more than one piece of meat (Extra topping), Then I want to add $2 on total price like ($10 + $2 = 12).
please help me??
Please use this action for adding the extra price on woocommerce cart.Now you need to work on the commented loop code and apply the simple login.Now I have added a summary for how you will work.
I have use it and now it is working on my local system.
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custome price
foreach ( $cart_object->cart_contents as $key => $value ) {
$productid = $value['product_id'];
$variationArr =$value['variation']; //it is an array have the value : meat and size i.e chicken and small
//In every loop you can count the number of products .
//Note: In array($variationArr),It have all the active attribute of this product which is created by admin in woocommece.
//so you can search it by loop;
/*
* Like
* foreach($variationArr as $k=>$v)
* {
* //here is the variation product size
* }
*
*/
//Now increase the price.
$price = $value['data']->price;
$extraPrice = 2;
$newPrice = $price + $extraPrice;
$value['data']->price = $newPrice;
}
}

Resources