Remove bundle item in the cart count woocommerce - wordpress

I building my ecommerce for sell wine with wordpress 4.2.2 and woocommerce 2.3.11
I bought the "Product Bundle" (v. 4.9.5) plugin for woocommerce.
I already insert this function in my function.php file
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}
because I need to sell bottles on multiple of 6.
Now I have this problem with the product bundled, because in the cart also the parent item is counted.
If I create a bundle with 6 bottle, in the cart I have the message "You need to buy in quantities of %s products" because the total count is 7 (6 bottles plus 1 bundle).
I write to woothemes support and I recive this answer:
By default, Bundle contents are not counted. A Bundle will be counted
as one item, no matter how many products it contains.
When using Product Bundles and needed to count the content, you need
to use the WC()->cart->get_cart_contents_count() method to count all
the cart items.
------ UPDATE -------
I try to add in my function the code from the answers, so now my function.php look like this:
<?php
/**
* Child-Theme functions and definitions
*/
// check that cart items quantities totals are in multiples of 6
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}
function so_28359520_remove_bundles_counting(){
global $woocommerce_bundles;
remove_filter( 'woocommerce_cart_contents_count', array( $woocommerce_bundles->display, 'woo_bundles_cart_contents_count' ) );
}
add_action( 'init', 'so_28359520_remove_bundles_counting' );
function so_28359520_cart_contents_count( $count ) {
$cart = WC()->cart->get_cart();
$subtract = 0;
foreach ( $cart as $key => $value ) {
if ( isset( $value[ 'stamp' ] ) && ! isset( $value[ 'bundled_by' ] ) ) {
$subtract += $value[ 'quantity' ];
}
}
return $count - $subtract;
}
add_filter( 'woocommerce_cart_contents_count', 'so_28359520_cart_contents_count' );
?>
but nothing happen. I also try a fresh wordpress and woocommerce installation with default theme (twenty thirteen and also twnty fifteen) for test if there is some javascript in the theme that interfering and change the quantity, but the result is the same.
If I have 1 bundles with 6 bottles I get the message from the first function.

I already answered this here. You need to disable Bundle's function and write your own to skip counting the bundle containers.
function so_28359520_remove_bundles_counting(){
global $woocommerce_bundles;
remove_filter( 'woocommerce_cart_contents_count', array( $woocommerce_bundles->display, 'woo_bundles_cart_contents_count' ) );
}
add_action( 'init', 'so_28359520_remove_bundles_counting' );
function so_28359520_cart_contents_count( $count ) {
$cart = WC()->cart->get_cart();
$subtract = 0;
foreach ( $cart as $key => $value ) {
if ( isset( $value[ 'stamp' ] ) && ! isset( $value[ 'bundled_by' ] ) ) {
$subtract += $value[ 'quantity' ];
}
}
return $count - $subtract;
}
add_filter( 'woocommerce_cart_contents_count', 'so_28359520_cart_contents_count' );
One thing to note, is that Javascript could be updating the count in your menu/widgets and not taking this in to account for some reason. However, when I "view source" I am getting the desired counts (ie: a bundle of 6 bottles is showing a count of 6).
Or as an alternative, you could modify your counting function to not count the bundle container. Untested:
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
if ( isset( $value[ 'stamp' ] ) && ! isset( $value[ 'bundled_by' ] ) ) {
continue; // skip the bundle container
} else {
$total_products += $values['quantity'];
}
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}

I was having issues with this until I realised I needed to use WC()->cart->get_cart_contents_count() rather than WC()->cart->cart_contents_count
Just thought I'd put this here in case anyone else was pulling their hair out...

Related

Add fee to WooCommerce shipping class but exclude local pickup

I'm using Add fee to Woocommerce Shipping Class without the use of zones or flat rate answer code, that allows me add an additional 'Fee' if any product from the 'Dangerous Goods' shipping class has been added to cart.
This is great as it allows me to cover the additional costs associated to packaging/shipping, however it is also adding the 'fee' when users select 'Local Pickup' shipping option.
I would love to exclude 'Local Pickup' from the additional fee if selected.
Therefore i use:
function fees_fees_fees() {
$shippingClasses['dangerous-goods'] = ['description' => 'Dangerous Goods Fee', 'fee' => 130];
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$shipping_class = get_the_terms( $values['product_id'], 'product_shipping_class' );
foreach($shippingClasses as $key => $val) {
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, [$key] ) ) {
WC()->cart->add_fee( __($val['description'], 'woocommerce'), $val['fee'] ); }
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'fees_fees_fees' );
However, I'm stuck on the next step. Any adivce?
The use of WC()->cart is not necessary, as $cart is already passed to the callback function
WC()->session->get( 'chosen_shipping_methods' ) can be used to get the chosen shipping method, then it is a matter of adding an if condition
So you get:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Get chosen shipping method
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_method = substr( $chosen_shipping_methods[0], 0, strpos( $chosen_shipping_methods[0], ':' ) );
// NOT for local pickup
if ( $chosen_shipping_method != 'local_pickup' ) {
// Settings
$shipping_classes['dangerous-goods'] = [ 'description' => 'Dangerous Goods Fee', 'fee' => 130 ];
// Loop though cart items
foreach ( $cart->get_cart() as $cart_item ) {
$shipping_class = get_the_terms( $cart_item['product_id'], 'product_shipping_class' );
foreach ( $shipping_classes as $key => $val ) {
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, [$key] ) ) {
$cart->add_fee( __( $val['description'], 'woocommerce' ), $val['fee'] );
}
}
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
Simply add check to slug.
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, [$key] ) && $shipping_class[0]->slug != 'local_pickup') {

Save value from a custom row added after the order table and display it in WooCommerce orders and emails

This code I wrote displays personalized information on the WooCommerce checkout page.
add_action( 'woocommerce_cart_totals_after_order_total', 'show_total_discount_cart_checkout', 9999 );
add_action( 'woocommerce_review_order_after_order_total', 'show_total_discount_cart_checkout', 9999 );
function show_total_discount_cart_checkout() {
$discount_total = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$subtotal = WC()->cart->get_product_subtotal( $product, $cart_item['quantity'] );
$total = WC()->cart->total;
$pctm = 90.00;
$valor_descontado = $total - ($total / 100 * $pctm);
$sale_price = '10%';
$discount = ( WC()->cart->total - $valor_descontado );
$discount_total = $discount;
}
if ( $discount_total > 0 ) {
echo '<tr><th>VOCÊ RECEBERÁ DE CASHBACK:</th><td data-title="You">' . wc_price( $discount_total + WC()->cart->get_discount_total() ) .'</td></tr>';
}
}
The result:
I need this information to also be displayed in WooCommerce orders and emails. I believe I can come up with a solution myself to display this value on several other pages, but can someone first tell me how to save/store the value of this calculation?
First of all, I've rewritten your existing code for the following reasons:
Requesting subtotals and totals is best done outside the foreach loop, because otherwise these values ​​will be overwritten every time
The result of $subtotal is not used anywhere in your code
Since the result of $subtotal is not used anyway, loop through the cart seems unnecessary
$sale_price is also not used anywhere in your code
Since $discount_total = $discount it is not necessary to use a new variable
A session variable is created/added
Your existing code, but optimized:
function action_woocommerce_after_order_total() {
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Get cart
$cart = WC()->cart;
// Getters
$cart_total = $cart->total;
$cart_discount_total = $cart->get_discount_total();
// Settings
$pctm = 90;
// Calculations
$discounted_value = $cart_total - ( $cart_total / 100 * $pctm );
$discount_total = $cart_total - $discounted_value;
// Greater than
if ( $discount_total > 0 ) {
// Result
$result = $discount_total + $cart_discount_total;
// The Output
echo '<tr class="my-class">
<th>' . __( 'VOCÊ RECEBERÁ DE CASHBACK', 'woocommerce' ) . '</th>
<td data-title="You">' . wc_price( $result ) . '</td>
</tr>';
// Set session
WC()->session->set( 'session_result', $result );
}
}
}
add_action( 'woocommerce_cart_totals_after_order_total', 'action_woocommerce_after_order_total', 10 );
add_action( 'woocommerce_review_order_after_order_total', 'action_woocommerce_after_order_total', 10 );
To answer your question:
Step 1) We get the result from the session variable and add it as order data, so that we can use/obtain this information everywhere via the $order object
// Add as custom order meta data and reset WC Session variable
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset
if ( WC()->session->__isset( 'session_result' ) ) {
// Get
$result = (float) WC()->session->get( 'session_result' );
// Add as meta data
$order->update_meta_data( 'result', $result );
// Unset
WC()->session->__unset( 'session_result' );
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );
Step 2) Use the woocommerce_get_order_item_totals filter hook, which will allow you to add a new row to the existing tables with the $result.
The new row will be added in:
Email notifications
Order received (thank you page)
My account -> view order
function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {
// Get meta
$result = $order->get_meta( 'result' );
// NOT empty
if ( ! empty ( $result ) ) {
// Add new row
$total_rows['total_result']['label'] = __( 'VOCÊ RECEBERÁ DE CASHBACK', 'woocommerce' );
$total_rows['total_result']['value'] = wc_price( $result );
}
return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );

Add To Cart button Text Change Based on Discount

This will change the text into "Add again?" when the customer clicks "Add to cart" and I'm wondering how to change this into applying a discount each time the button is clicked.
Code:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_add_to_cart_again' );
function woo_add_to_cart_again() {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if( get_the_ID() == $_product->id ) {
return __('Add Again', 'woocommerce');
}
}
return __('Add to cart', 'woocommerce');
}
When clicked the first time, add to cart as normal but change the button text into "Buy again & Get 5% OFF", after pressed the 2nd time, text changes into "Buy 3 and get 10% OFF" and the discount should apply to the product, not the cart.
I would like for this to be a checkbox option beside "Downloadable" in WooCommerce Admin when creating a new product. Any help is highly appreciated.
first to change the text based on the quantity i just added an if condition to your function to check the quantity for that specific product in the cart and change the text accordingly as follow:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_add_to_cart_again' );
function woo_add_to_cart_again() {
global $woocommerce;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $values['quantity'] == 1 && get_the_ID() == $_product->id ) {
return __( 'Buy again & Get 5% OFF', 'woocommerce' );
}
if ( $values['quantity'] == 2 && get_the_ID() == $_product->id ) {
return __( 'Buy 3 and get 10% OFF', 'woocommerce' );
}
if ( $values['quantity'] > 2 && get_the_ID() == $_product->id ) {
return __( 'Add Again', 'woocommerce' );
}
}
return __( 'Add to cart', 'woocommerce' );
}
Note: if you want to change the text in the archive page too you can use woocommerce_product_add_to_cart_text hook and added it to the above code as follow:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_add_to_cart_again' );
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_add_to_cart_again' );
Then we need to calculate the price for those products which is qualified for the discount and add the discount based on the product prices.
We are going to use woocommerce_cart_calculate_fees to insert this discount to our cart as follow :
add_action( 'woocommerce_cart_calculate_fees', 'add_discount' );
function add_discount( WC_Cart $cart ) {
$discounts = []; //Store the disocunts in array
foreach ( $cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $values['quantity'] == 2 ) {
// Calculate the discount amount
$product_price = ( $_product->get_sale_price() ) ? $_product->get_sale_price() : $_product->get_regular_price();
$price = $product_price * 2;
array_push( $discounts, $price * 0.05 ); //Push the discount
}
if ( $values['quantity'] > 2 ) {
// Calculate the discount amount
$product_price = ( $_product->get_sale_price() ) ? $_product->get_sale_price() : $_product->get_regular_price();
$price = $product_price * $values['quantity'];
$discount = $price * 0.1;
array_push( $discounts, $price * 0.1 );//Push the discount
}
}
$cart->add_fee( 'Your Disocunt', -array_sum( $discounts ) );
}
Updated:
To Change the add_to_cart text when using Ajax actually it's already answered in here By #LoicTheAztec at this link and with little modification you can achieve your target goal as follow:
add_action( 'wp_footer', 'change_add_to_cart_jquery' );
function change_add_to_cart_jquery() {
if ( is_shop() || is_product_category() || is_product_tag() ) : ?>
<script type="text/javascript">
(function ($) {
$('a.add_to_cart_button').click(function () {
$this = $(this);
if (typeof $($this).attr('data-qty') == 'undefined') {
$($this).text('Buy again & Get 5% OFF');
$($this).attr('data-qty', 1);
return;
}
if ($($this).attr('data-qty') == 1) {
$($this).text('Buy 3 and get 10% OFF');
$($this).attr('data-qty', 2);
return
}
$($this).text('Add Again');
});
})(jQuery);
</script>
<?php
endif;
}
of course the code above has been tested.

how to remove a product or category from cart count?

I would like to know, in Wordpress + WooCommerce: How to remove a specific product or category from the cart count ?
I'm selling a product associated with a second product (which is a subscription) , and when I add 5 of this product to the Basket, the Mini Cart in the header shows 10 products.
This can be scary for the customers. I took a look at the similar questions, but it didn't work for the Cart in the header.
You can filter the cart quantity via woocommerce_cart_contents_count. Change slug_of_category_to_ignore to suit.
/**
* Filters the reported number of cart items.
* Counts only items NOT in certain category.
*
* #param int $count
* #return int
*/
function so_43498002_cart_contents_count( $count ) {
$cart_items = WC()->cart->get_cart();
$subtract = 0;
foreach ( $cart_items as $key => $value ) {
if ( has_term( 'slug_of_category_to_ignore', 'product_cat', $value['product_id'] ) ) {
$count -= $value[ 'quantity' ];
}
}
return $count;
}
add_filter( 'woocommerce_cart_contents_count', 'so_43498002_cart_contents_count' );
Try This
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$total_products = WC()->cart->cart_contents_count;
$multiples = 6;
$totale = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$prodotti = $values['data'];
if( ! has_term( array( 169, 152 ), 'product_cat', $prodotti->id ) ){
$totale += $values['quantity'];
}
}
echo $totale;
if ( ( $totale % $multiples ) > 0 ){
wc_add_notice( sprintf( __('You need to buy in multiples of %d products', 'your-textdomain'), $multiples ), 'error' );
}
}

Woocommerce Order Quantity in Multiples

I'm trying to restrict woocommerce to only selling in set quantities of 5, 10 or 15.
The code snippet below ( which i found on this forum) allows me to set a minimum quantity of 5 but i'm wondering if anybody could advise if it can be modified to allow 5, 10 or 15.
I appreciate any help you can offer.
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
function wc_minimum_order_amount() {
global $woocommerce;
$minimum = 5;
if ( $woocommerce->cart->cart_contents_count < $minimum ) {
$woocommerce->add_error( sprintf( 'Cards can only be purchased in multiples of %s Please ammend your order.' , $minimum ) );
}
}
Thanks to Gareth for his answer, but i actually found a better way of achieving what i need, just posting in case anybody else needs it.
I found it better to restrict the cart to sell in multiples of 5 which can be achieved with the following code.
// check that cart items quantities totals are in multiples of 5
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
global $woocommerce;
$multiples = 5;
$total_products = 0;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 )
$woocommerce->add_error( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ) );
}
WooCommerce Allow Checkout in Multiples Only, To force the customer to add multiples of a certain quantity to the cart before being able to checkout
<?php
// check that cart items quantities totals are in multiples of 6
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}
// Limit cart items with a certain shipping class to be purchased in multiple only
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities_for_class' );
function woocommerce_check_cart_quantities_for_class() {
$multiples = 6;
$class = 'bottle';
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = get_product( $values['product_id'] );
if ( $product->get_shipping_class() == $class ) {
$total_products += $values['quantity'];
}
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to purchase bottles in quantities of %s', 'woocommerce'), $multiples ), 'error' );
}
?>
Not tested but this should work, basically just added the different minimums into an array so the check for $minimum will check all 3 amounts
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
function wc_minimum_order_amount() {
global $woocommerce;
$minimum = array('5,'10','15');
if ( $woocommerce->cart->cart_contents_count < $minimum ) {
$woocommerce->add_error( sprintf( 'Cards can only be purchased in multiples of %s Please ammend your order.' , $minimum ) );
}
}
Try using WooCommerce Advanced Product Quantities, it should take care of this for you. Otherwise the below functions are what it uses to get the right step and minimum values for both the cart and product page. Keep in mind that if you only change the input values you'll have to validate them on add to cart and checkout (again the plugin linked below does all of this for you).
http://wordpress.org/plugins/woocommerce-incremental-product-quantities/
Otherwise this filter would probably help for the cart:
add_filter( 'woocommerce_quantity_input_step', 'input_step_value', 1, 2);
function input_step_value( $default, $product ) {
return 5;
}
And this one for the product page:
add_filter( 'woocommerce_quantity_input_args', 'input_set_all_values', 1, 2 );
function input_set_all_values( $args, $product ) {
$args['step'] = 5;
$args['min_value'] = 5;
return $args;
}

Resources