Split cart items when quantity is updated on cart page in WooCommerce - wordpress

I want to split cart items of same product in individual lines. When I increase quantity on single product page and add to cart, it shows as separate cart items.
Im using WooCommerce - Treat cart items separate if quantity is more than 1 answer code.
I want when quantity is updated on cart page and clicked on 'Update cart', then items must split on individual lines.
How can I do that?

The code below will split items on individual lines when quantity is updated on the cart page.
Comment with explanation added to the code.
function on_action_cart_updated( $cart_updated ) {
if ( $cart_updated ) {
// Get cart
$cart_items = WC()->cart->get_cart();
foreach ( $cart_items as $cart_item_key => $cart_item ) {
$quantity = $cart_item['quantity'];
// If product has more than 1 quantity
if ( $quantity > 1 ) {
// Keep the product but set its quantity to 1
WC()->cart->set_quantity( $cart_item_key, 1 );
// Run a loop 1 less than the total quantity
for ( $j = 1; $j <= $quantity -1; $j++ ) {
// Set a unique key.
$cart_item['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );
// Get vars
$product_id = $cart_item['product_id'];
$variation_id = $cart_item['variation_id'];
$variation = $cart_item['variation'];
// Add the product as a new line item with the same variations that were passed
WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item );
}
}
}
}
}
add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );

Related

Request - How to add Handling Fee based on Category of Product? [duplicate]

I already found this code here and it works for like 80/90% for me (see below).
This code adds 60 euro to my cart when there is a product from category ID 349 in the cart. When I add a product from that category to my cart when the cart is empty it works fine. But when there is already a product in my cart from a different category and then I add the product with category 349 it doesn't add the 60 euro extra fee. How is this possible?
function woo_add_cart_fee() {
$category_ID = '349';
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
// Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values['product_id'], 'product_cat' );
// Because a product can have multiple categories, we need to iterate through the list of the products category for a match
foreach ($terms as $term) {
// 349 is the ID of the category for which we want to remove the payment gateway
if($term->term_id == $category_ID){
$excost = 60;
}
}
$woocommerce->cart->add_fee('Extra bezorgkosten kunstgras', $excost, $taxable = false, $tax_class = '');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
The code you are using is a bit outdated and you should use has_term() Wordpress conditional function to target a product category this way:
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
$categories = array('349');
$fee_amount = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
$fee_amount = 60;
}
// Adding the fee
if ( $fee_amount > 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Extra bezorgkosten kunstgras", "woocommerce" ), $fee_amount, false );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
A fee of 60 will always be added if there is in cart an item from 349 product category ID.
I found a solution like the following. Note that I kept adding a fee, because I started from a previous snippet. You can apply an existing discount or calculate a different total according to your needs.
In this case, I apply a negative fee - like a discount - according to a >= 300 total value of the cart, whose values would be -25% only for local_pickup shipping method, calculating taxes in addition.
function discount_to_cat(){
// thanks to LoicTheAztec's snippet
$cat_in_cart = false;
// Loop through all products in the Cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_term( 'category_to_pick', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
$tot_category_price = $cart_item['data']->get_price();
$tot_category_qty = $cart_item['quantity'];
$tot_category = $tot_category_price * $tot_category_qty;
break;
}
} global $product;
$total = WC()->cart->subtotal;
$discount_label = "";
if($total >= 300){
$discount_label=15;
}
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = explode(':',$chosen_methods[0]);
if($chosen_shipping[0]=='local_pickup'){
$discount_label=25;
}
$discount_applied = ($total-$tot_category)*$discount_label/100;
if($discount_label!=""){
$discount_applied_net = ($discount_applied/1.1); //1.1 according taxes for shipping
WC()->cart->add_fee( "Discount applied: ($discount_label%)", -$discount_applied_net, false );
}
}
add_action( 'woocommerce_cart_calculate_fees','discount_to_cat' );

Woocommerce : programmatically set a discount for the first item ordered, but inventory based

I'm building a website where i'll sell some fine art prints and i would like to set an automated discount when a customer buy the first print of a serie. Each of my prints are limited to 15 pieces and i would like to set a 30% discount for the first sell (#1/15) of each series. Then, for the next prints (#2 to #15), price goes back to normal.
Edit :
I did progress on my problem ! I did some research and tried a lot of different things and i found how to set the custom price i wanted on my product page (regular price + discount price) with the rule to only apply it if the related item available stock is 15.
regular price + discount price
And here's the code is used :
// Generating the product "regular price"
add_filter( 'woocommerce_product_get_regular_price', 'dynamic_regular_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'dynamic_regular_price', 10, 2 );
function dynamic_regular_price( $regular_price, $product ) {
$stock_qte = $product->get_stock_quantity();
if( empty($regular_price) || $regular_price == 0 )
return $product->get_price();
else
return $regular_price;
}
// Generating the product "sale price"
add_filter( 'woocommerce_product_get_sale_price', 'dynamic_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'dynamic_sale_price', 10, 2 );
function dynamic_sale_price( $sale_price, $product ) {
$stock_qte = $product->get_stock_quantity();
if( $stock_qte == '15')
return $product-> get_regular_price() * 0.7;
else
//return $product->get_regular_price();
return $regular_price;
};
// Displayed formatted regular price + sale price
add_filter( 'woocommerce_get_price_html', 'dynamic_sale_price_html', 20, 2 );
function dynamic_sale_price_html( $price_html, $product ) {
$stock_qte = $product->get_stock_quantity();
if( $stock_qte == '15')
$price_html = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ), wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ) ) . $product->get_price_suffix();
else
$price_html = wc_price(wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ). $product->get_price_suffix());
return $price_html;
}
It's almost working but the code related to the cart values updates is not fully working. The cart sub-total is good and take count of the discount but the individual price of each product is not updated and shown as without discount. It's the same on the cart page.
cart (from mini cart)
cart (cart page)
add_action( 'woocommerce_before_calculate_totals', 'alter_price_cart', 9999 );
function alter_price_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// IF CUSTOMER NOT LOGGED IN, DONT APPLY DISCOUNT
//if ( ! wc_current_user_has_role( 'customer' ) ) return;
// LOOP THROUGH CART ITEMS & APPLY 30% DISCOUNT
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$price = $product->get_price();
$cart_item['data']->set_price( $price * 0.7 );
}
}
I'll also have to add the stock availability logic for the mini-cart / cart / checkout page but i'll do that in a second time.
I must have made some mistakes in the loop throught the cart but i cannot catch the issue :( Any idea about how to hook the price of each product and change the displayed value ?
Have a nice day,
Quentin

Woocommerce: Different order_id for same products in cart

I am using Woocommerce plugin with WP and when I add to cart an item and then I add to cart the same item again, at the cart page it's displayed as one item with quantity of two and with one order_id. What I want is to be able to add to cart multiple times the same product and each product to get a unique order_id. Is there a way to do that? Thank you.
function bbloomer_split_product_individual_cart_items( $cart_item_data, $product_id ){
$unique_cart_item_key = uniqid();
$cart_item_data['unique_key'] = $unique_cart_item_key;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_split_product_individual_cart_items', 10, 2 );
//add_filter( 'woocommerce_is_sold_individually', '__return_true' );
#***************************************************
add_action( 'woocommerce_add_to_cart', 'mai_split_multiple_quantity_products_to_separate_cart_items', 10, 6 );
function mai_split_multiple_quantity_products_to_separate_cart_items( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// If product has more than 1 quantity
if ( $quantity > 1 ) {
// Keep the product but set its quantity to 1
WC()->cart->set_quantity( $cart_item_key, 1 );
// Run a loop 1 less than the total quantity
for ( $i = 1; $i <= $quantity -1; $i++ ) {
/**
* Set a unique key.
* This is what actually forces the product into its own cart line item
*/
$cart_item_data['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );
// Add the product as a new line item with the same variations that were passed
WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item_data );
}
}
}

How to get the value of the steps quantity product added to WooCommerce cart?

I used this code to filter the products added to the cart of a certain category (id = 70).
My goal is to count the number of step quantities added to the cart of a product belonging to the '70' category.
Example:
Minimum quantity: 0
Step: 100
I added the product to the cart with 300 quantities.
So the step number is 3.
Is there a way to get the number of step quantities of a product added to the cart?
// Utility function that count specific product category cart items
add_shortcode('palletcompleto', 'cat_cart_count');
function cat_cart_count( $term_ids ) {
$quantity = 0; // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_product_category( $cart_item['product_id'], array( 70 ) ) ) {
$quantity += $cart_item['step_quantity'];
}
}
// Returning category count
return $quantity == 0 ? false : $quantity;
}
I am using some code like has_product_category() function from this thread:
Set item quantity to multiples of “x” for products in a specific category in Woocommerce
// Custom conditional function that checks also for parent product categories
function has_product_category( $product_id, $category_ids ) {
$term_ids = array(); // Initializing
// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
if( $term->parent > 0 ){
$term_ids[] = $term->parent; // Set the parent product category
$term_ids[] = $term->term_id;
} else {
$term_ids[] = $term->term_id;
}
}
return array_intersect( $category_ids, array_unique($term_ids) );
}

synced force sell based on product quantity in woocommerce

I want to force sell based on the product quantity if the customer adds 5 product 1 accessories should add. if they add more then 5, 2 accessories should add.
so the accessories should add in the multiple of five.
Try this:
add_action( 'woocommerce_add_to_cart', 'prefix_add_additional_product', 10, 6 );
/**
* Adds additional product to cart based on the quantity of an added product
*/
function prefix_add_additional_product( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Get the cart
$cart = WC()->cart->get_cart();
// Nothing, if the cart is empty
if ( 0 == count( $cart ) ) {
return;
}
// Enter the free product ID
$additional_product_id = 96;
// Don't add accessory when adding the same accessory
$added_product_id = 0 < $variation_id ? $variation_id : $product_id;
if ( $added_product_id == $additional_product_id ) {
return;
}
// You can add checks for specific product ID or some other requirements here
$additional_product_quantity = (int) ( $quantity / 5 );
WC()->cart->add_to_cart( $additional_product_id, $additional_product_quantity );
}
https://gist.github.com/vanbo/f42cfa8bdf593013f77dda605a9876bb
The code should add the $additional_product_id to cart with a quantity that matches the amount of times the added product to cart quantity can be devided by 5.
The code is hooked to the add to cart hook.

Resources