Get cost value of chosen shipping method at checkout of Woocommerce - woocommerce

In functions.php of my child theme I have custom script like this:
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process1');
function my_custom_checkout_field_process1() {
//do something
}
To do some calculations I need to get the cost of chosen shipping method. How to do that?

I got it!
$cart = WC()->cart;
$total = __( 'Free!', 'woocommerce' );
if ( 0 < $cart->get_shipping_total() ) {
if ( $cart->display_prices_including_tax() ) {
$total = $cart->shipping_total + $cart->shipping_tax_total;
} else {
$total = $cart->shipping_total;
}
}

Related

Discount amount not correct for woocommerce_coupon_get_discount_amount

I am trying to discount the cheapest item in the cart if my coupon type is used:
add_filter('woocommerce_coupon_get_discount_amount', 'wc_cpn_disc', 10, 5);
function wc_cpn_disc($discount, $discounting_amount, $cart_item, $single, $coupon) {
// IF TYPE MATCHES PERFORM CUSTOM CALCULATION
if ($coupon->type == 'cheapest_free'){
global $woocommerce;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$product_price[] = get_option('woocommerce_tax_display_cart') == 'excl' ? $_product->get_price_excluding_tax() : $_product->get_price_including_tax(); /*Store all product price from cart items in Array */
}
$lowestprice = min($product_price);
$discount = number_format((float)$lowestprice/10,2,'.','');
}
return $discount;
}
The discount amount is very weird - no matter what I try, it never comes out to the value I expect. At first I thought it was a percentage discount, but I expect this to be a fixed amount. I have tried running my get lowest price bit of function elsewhere on the site and it returns 1.195 when the lowest value item is 11.95 - so I know that part works. But the discount on a total basket of 265.60 is 23.90 - I just don't get it!
I just want to get the lowest priced item in the cart, and discount that amount.
I managed to solve this with the help of Bossman and a couple of other threads. It turns out I needed to change my method - full code below.
add_filter('woocommerce_coupon_get_discount_amount', 'tfcc_cheapest_free', 10, 5);
function tfcc_cheapest_free($discount, $discounting_amount, $cart_item, $single, $coupon) {
// IF TYPE MATCHES PERFORM CUSTOM CALCULATION
if ($coupon->type == 'cheapest_free'){
$items_prices = [];
$items_count = 0;
// Loop through cart items
foreach( WC()->cart->get_cart() as $key => $item ){
// Get the cart item price (the product price)
if ( wc_prices_include_tax() ) {
$price = wc_get_price_including_tax( $item['data'] );
} else {
$price = wc_get_price_excluding_tax( $item['data'] );
}
if ( $price > 0 ){
$items_prices[$key] = $price;
$items_count += $item['quantity'];
}
}
// Only when there is more than one item in cart
if ( $items_count > 1 ) {
asort($items_prices); // Sorting prices from lowest to highest
$item_keys = array_keys($items_prices);
$item_key = reset($item_keys); // Get current cart item key
// Targeting only the current cart item that has the lowest price
if ( $cart_item['key'] == $item_key ) {
return reset($items_prices)/$cart_item['quantity']; // return the lowest item price as a discount
}
} else {
return 0;
}
}
}
I hope this might help someone else out who needs a similar feature in the future.

Add Badge to New products

i'm trying to make a change on my Woocomerce Store. I want to add a badge to my New Products, my theme doesn't support this so i want to re-use a function that i find for Sale Products and Apply to New products but i'm not finding how to change it to make it work.
I have the next function that works for add percent to sale badge, i want just to modify for New products only adding the span with the class and text.
function custom_product_sale_flash( $output, $post, $product ) {
global $product;
if($product->is_on_sale()) {
if($product->is_type( 'variable' ) )
{
$regular_price = $product->get_variation_regular_price();
$sale_price = $product->get_variation_price();
} else {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
}
$percent_off = (($regular_price - $sale_price) / $regular_price) * 100;
return '<span class="onsale">' . round($percent_off) . '% OFF</span>';
}
}
add_filter( 'woocommerce_sale_flash', 'custom_product_sale_flash', 11, 3 );
Thank you in advance.
You can use one of the actions used in the file templates/content-product.php to hook into the rendering of the HTML.
add_action('woocommerce_before_shop_loop_item_title', function() {
global $post;
$days = 5;
$offset = $days*60*60*24;
if ( get_post_time() < date('U') - $offset )
return '<span class="new-product">NEW</span>';
}
});

How to make shipping cost free in woocommerce?

I have a woocommerce website in which there are 2 products, one product has free shipping but other has paid shipping if they are added separately in cart. Now I have a scenario that if some customer adds both free and paid shipping products together in shopping cart then shipping should become free for that whole order. How can I achieve this?
Thanks,
Mohammad
try this... just paste this in your theme's functions.php and replace the id in $products_to_look = array( 34 ); below.
add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates' );
function woocommerce_package_rates( $rates ) {
if ( ! WC()->cart->is_empty() ) {
$products_to_look = array( 34 ); // ids of products separated by comma.
$found = false;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $found = in_array( $cart_item['product_id'], $products_to_look ) ) {
break;
}
}
}
if ( $found ) {
foreach($rates as $key => $rate ) {
$rates[$key]->label = 'Free shipping'; // change label to Free shipping...
$rates[$key]->cost = 0; // cost is set to 0.
}
}
return $rates;
}
Further readings: WooCommerce shipping fee that changes when condition is met

Shipping Rates based on Product Quantity on woocommerce

I want to set shipping cost quantity wise on my woocommerce theme. I want to do this option :
For 1 to 5 products shiping cost will be 15%.
More than 5 products whipping cost will be $6.99 .
Can i add this shipping option without a plugin ?
You need to hook a function to woocommerce_calculate_totals action which is triggered right before calculating the final cart total. The woocommerce_calculate_totals action provides the WC_Cart instance, on which you can perform manipulation as per your requirement.
add_action('woocommerce_calculate_totals', 'modify_shipping_totals');
function modify_shipping_totals($cart) {
if($cart->get_cart_contents_count() < 6) {
$cart->shipping_total = ( 15/100 ) * $this->cart_contents_total;
// shipping cost will be 15% of cart content total
// you may also want to modify the shipping tax.
$cart->shipping_tax_total = 0;
} else {
$cart->shipping_total = 6.99;
$cart->shipping_tax_total = 0;
}
}
For further reference regarding changable variables refer to WC_Cart documentation.
// **Note**: This code is working only when you set Flat rate Settings
// cost value is 1
add_filter( 'woocommerce_package_rates', 'custom_package_rates', 10, 2 );
function custom_package_rates( $rates, $packages ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$cart_count = WC()->cart->get_cart_contents_count();
$cart_total = WC()->cart->cart_contents_total;
foreach($rates as $rate_key => $rate_values ) {
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
if( $method_id == 'flat_rate' ){
if( $cart_count < 99 ){
$flat_rate_value = 4.95; //"Applay Flat rate less then 99 quatity"
$cart_10_percent = 0; // No percent discount
}
if( $cart_count > 99 ){
$flat_rate_value = 9.95; // "Applay Flat rate greater then 99 quatity"
$cart_10_percent = 0; // No percent discount
}
$rate_cost = $flat_rate_value > $cart_10_percent ? $flat_rate_value - $cart_10_percent : 0;
// Set the new calculated rate cost
$rates[$rate_id]->cost = number_format( $rates[$rate_id]->cost * $rate_cost, 2 );
}
}
return $rates;
}
The Pranav solution works if you call the add_action inside the init hook, like this:
function init_shop(){
add_action('woocommerce_calculate_totals', 'modify_shipping_totals', 10);
}
add_action( 'init', 'init_shop');

Woocommerce shopping cart column

How add custom column to woocommerce shopping cart and then add info of some input from this column to order, checkout page and to email?
Actually i need add friends list from buddypress to each product row(price must depends on how many friends checked).
Here i found suggestion, but it`s partly helpfull WooCommerce: Add input field to every item in cart
wp community also keep silence
http://wordpress.org/support/topic/woocommerce-custom-column-in-cart?replies=1
what i do - its just add list of avalaible friends and no idea how can I save data on update cart or proceed.
if ( bp_has_members( 'user_id=' . bp_loggedin_user_id() ) ){
function ggUserFrom(){
$arrUsers = array();
while ( bp_members() ){
bp_the_member();
$arrUsers[ bp_get_member_user_nicename() ] = bp_get_member_user_nicename();
}
return $arrUsers;
}
echo "<div class='friends-holder'>";
foreach ( ggUserFrom() as $friend ){
echo '<p><input type="checkbox" name="cart['.$cart_item_key.'][friendsfromcart]" value="'.$friend.'">
<span>'.$friend.'</span></p>';
}
echo "</div>";
}
Im seek ANY info about this question.
Here, since user may choose multiple checkboxes, it may contain multiple values. Therefore, we have used "serialize" function.
for example,
add_filter( 'woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
if(!function_exists('wdm_get_cart_items_from_session'))
{
function wdm_get_cart_items_from_session($item,$values,$key)
{
$item['custom_field_name'] = isset( $values['friendsfromcart'] )? serialize($values['friendsfromcart']) : '';
return $item;
}
}
While you are adding Order meta data, you can fetch individual values and add corresponding keys as follows,
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values)
{
$user_custom_values = unserialize($values['friendsfromcart']);
if(count($user_custom_values) > 0)
{
foreach($user_custom_values as $single_value)
{
wc_add_order_item_meta($item_id,ucfirst($single_value),single_value);
}
}
}
since order meta will be sent in E - mail.
Thank for reply and - yes, variable isset in checkout page, but his empty in
var_dump($_POST)...
...[custom_field_name] =>
...
and ofc is empty in email.
Perhaps i incorrect send it ?
name="friendsfromcart"
or send values its a array and must send:
name="friendsfromcart[]"
or
name="[friendsfromcart]"
or need session key
name="cart['.$cart_item_key.'][friendsfromcart]" ?
It works, array in cart but something wrong with unserialize:
add_action( 'init', 'update_cart_action', 9);
function update_cart_action() {
global $woocommerce;
if ( ( ! empty( $_POST['update_cart'] ) || ! empty( $_POST['proceed'] ) ) && $woocommerce->verify_nonce('cart')) {
$cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if ( isset( $cart_totals[ $cart_item_key ]['friendsfromcart'] ) ) {
$woocommerce->cart->cart_contents[ $cart_item_key ]['friendsfromcart'] = $cart_totals[ $cart_item_key ]['friendsfromcart'];
}
}
}
}
}
add_filter( 'woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key){
$item['friendsfromcart'] = isset( $values['friendsfromcart'] )? serialize($values['friendsfromcart']) : '';
return $item;
}
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values){
$user_custom_values = unserialize($values['friendsfromcart']);
if(count($user_custom_values) > 0){
foreach($user_custom_values as $single_value){
wc_add_order_item_meta($item_id,ucfirst($single_value),single_value);
}
}
}

Resources