Get woocommerce carts total amount
You need to call the global variable to ensure that it gets the correct values.
If you add
global $woocommerce;
just before
$amount2 = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );
that should solve your problem.
Get cart total as a float number in WooCommerce 3+
You can refer to WooCommerce WC_Cart
official documentation
This should work:
WC()->cart->get_total("anything_else_than_'view'");
Explanations:
Thanks to btomw that pointed out that an argument need to be defined in WC_Cart
get_total()
method. If you call this method without defining an argument (that should be anything else than 'view' string), the output is going to be the formatted total price, as 'view'
default argument will be used by this method. So if you want to get a float value (non formatted)
, set as argument anything else that is not 'view', even an empty string like ''
. As you can see on this method documentation, it's for backwards compatibility since WooCommerce 3.2.
Get total cart woocommerce
You try
$app= (float) preg_replace( '/[^0-9\.]/', '', $woocommerce->cart->get_cart_total() );
Or
$app = str_replace('$','',$woocommerce->cart->get_cart_total() );
the solution depends on the type of currency that is occupied in this case the euro occupied, so we had to replace the euro in htmlentities as shown here
str_replace ( '& euro;', '', $ woocommerce-> cart-> get_cart_total ());
Note: trim '& euro'
Get cart item name, quantity all details woocommerce
Try this :
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
echo "<b>".$_product->get_title().'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
}
?>
To get Product Image and Regular & Sale Price:
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id() );
//product image
$getProductDetail = wc_get_product( $values['product_id'] );
echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )
echo "<b>".$_product->get_title() .'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
/*Regular Price and Sale Price*/
echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
}
?>
How to get discount amount to set cart item prices to zero in WooCommerce before calculating totals
You can get cart totals from the current customer session (WC_Session
).
Inside the hook woocommerce_before_calculate_totals
use WC()->session->get('cart_totals');
to get cart totals.
You can also check if a product belongs to a specific product category or not via the Wordpress has_term
function.
In your code, you are subtracting both the discount tax and the discount amount. If the products are priced excluding taxes, perhaps you should only subtract the discount amount.
The optimized function is:
// Set cart item prices to zero based on cart total.
add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_cart_items_price', 99, 1 );
function conditionally_change_cart_items_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Defines the gift product category id.
$gift_product_cat_id = 405;
// Set the threshold for applying prices to zero.
$gift_product_price_limit = 100;
// Gets the total cart discount from the current customer session.
$cart_totals = WC()->session->get('cart_totals');
$total_discount = $cart_totals['discount_total'] + $cart_totals['discount_tax'];
// Calculates the sum of the cart item prices that do not belong to the gift product category.
$total = 0;
foreach ( $cart->get_cart() as $cart_item ) {
if ( ! has_term( $gift_product_cat_id, 'product_cat', $cart_item['product_id'] ) ) {
$total += (float) $cart_item['line_subtotal'];
}
}
// If the product subtotal (including discounts) is greater than or equal to the threshold, set the gift item prices to zero.
if ( ( $total - $total_discount ) >= $gift_product_price_limit ) {
foreach ( $cart->get_cart() as $cart_item ) {
if ( has_term( $gift_product_cat_id, 'product_cat', $cart_item['product_id'] ) ) {
$cart_item['data']->set_price( 0 );
}
}
}
}
The code has been tested and works. Add it to your active theme's functions.php.
Get the cart totals non formatted values as float numbers in WooCommerce
Using WC()->cart
(the WC_Cart
class object) you can use methods or access properties listed on the following WC_Cart
class documentation Api.
So with WC()->cart
you can access the properties directly and get non formatted values using:
echo WC()->cart->subtotal;
echo WC()->cart->subtotal_ex_tax;
echo WC()->cart->total;
echo WC()->cart->total_ex_tax;
echo WC()->cart->cart_contents_total;
You will get float numbers for all. Remember that WC()->cart
is a live object.
WC()->cart
replace totallyglobal $woocommerce;
with$woocommerce->cart
, so no need to use outdatedglobal $woocommerce;
with it…
Related official documentation: WC_Cart
class api, methods and properties
How to use cart total to change cart items prices in WooCommerce
You can simply not use cart total in woocommerce_before_calculate_totals
when you want to alter cart item price for many reasons…
Instead you will get cart item subtotal inside woocommerce_before_calculate_totals
hook. On the code below I use the discounted cart item subtotal including taxes:
add_action('woocommerce_before_calculate_totals', 'customize_cart_item_prices');
function customize_cart_item_prices( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding the hook repetition for price calculations
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 1000; // Min subtotal
$discount_rate = 0.2; // price discount rate (20%)
$cart_items = $cart->get_cart();
// Getting non discounted cart items subtotal
$subtotal_excl_tax = array_sum( wp_list_pluck( $cart_items, 'line_subtotal' ) );
$subtotal_tax = array_sum( wp_list_pluck( $cart_items, 'line_subtotal_tax' ) );
// Getting discounted cart items subtotal
$total_excl_tax = array_sum( wp_list_pluck( $cart_items, 'line_total' ) );
$total_tax = array_sum( wp_list_pluck( $cart_items, 'line_tax' ) );
if( ( $total_excl_tax + $total_tax ) >= $threshold_amount ) {
// Loop through cart items
foreach ( $cart_items as $item ) {
$price = $item['data']->get_price(); // Get price
$item['data']->set_price( $price * ( 1 - $discount_rate ) ); // Set new price
}
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
See on Change cart item prices in Woocommerce 3 answer code, to see how to handle minicart displayed custom cart item price.
Related Topics
How to Center the Text in Phpexcel Merged Cell
How to Prevent a User from Directly Accessing My HTML Page by Writing Url
How to Check If MySQL Results Returned Empty in PHP
How to Pass a PHP Variable Using the Url
How to Get Data from Another Table Using Id from Another Table
Comparing Date from Variable to MySQL Date
Calculate Size in Bytes of Json Payload Including It in the Json Payload in PHP
Selected Value Get from Db into Dropdown Select Box Option Using PHP MySQL Error
Extension Mysqli Is Missing, Phpmyadmin Doesn't Work
Dynamic Menu and Role Permission in Codeigniter
How to Generate Unique Random Value for Each User in Laravel and Add It to Database
How to Change PHP Version in Xampp
The Get Method Is Not Supported for This Route. Supported Methods: Put. But I'M Using Put
Php Json String, Escape Double Quotes for Js Output
Sending Message in Telegram Bot With Images
How to Get Multiple Value from Post Variable Using Same Name