Woocommerce - custom functions runs only on update cart - wordpress

I wrote a very small function to disable installation as a method (from table rate shipping plugin) if a product is not in the cart or if the quantity of that product in the cart is less than 6.
This works, but only when I click on "update cart" button and not, for example, when I click on cart.
here's the function, directly from my function.php file in my custom theme:
function disable_installation_for_less_than( $rates ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$installation = $rates['table_rate_shipping_installation'];
foreach ( $items as $item => $values ) {
$productID = $values['product_id'];
$productQuantity = $values['quantity'];
unset( $rates['table_rate_shipping_installation'] );
if ( $productID == 2412 ) {
if ( $productQuantity < 6 ) {
unset( $rates['table_rate_shipping_installation'] );
} else {
array_push($rates, $installation);
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'disable_installation_for_less_than', 10, 3 );
Any idea why? am I using the wrong hook?
Thanks for any help
Also, rather then un-setting the installation and re-set it only when needed, is there a better way to say "if this product is NOT in the cart" then remove this?
thanks

Ok, I managed to solve it this way:
function disable_installation_for_less_than( $rates ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$showInstallation= false;
foreach ( $items as $item => $values ) {
$productID = $values['product_id'];
$productQuantity = $values['quantity'];
if ( $productID == 2412 ) {
$showInstallation= true;
if ( $productQuantity < 6 ) {
unset( $rates['table_rate_shipping_installation'] );
}
}
}
if ($showInstallation== false){
unset( $rates['table_rate_shipping_installation'] );
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'disable_installation_for_less_than', 10, 2 );
It's working now.

Related

WooCommerce, disable shipping based on an acf field

I added a true/false field inside the user profile through acf.
I need to hide a specific shipment if this field is selected or not.
If selected, the shipment must be hidden.
This is my code:
function filter_woocommerce_package_rates( $rates, $package ) {
$user_id = get_current_user_id();
$verified=false;
$acf_field=get_user_meta( $user_id, 'fast_shipping', true );
if($acf_field) $verified=true;
// Loop trough
foreach ( $rates as $rate_id => $rate ) {
if ( $verified ) {
unset( $rates['flat_rate:8'] );
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
But nothing is hidden.
Can you please try below code:
function filter_woocommerce_package_rates( $rates, $package ) {
$user_id = get_current_user_id();
$verified=false;
$acf_field=get_user_meta( $user_id, 'fast_shipping', true );
if(is_bool($acf_field) == 1) $verified=true;
if ( is_bool($verified) == 1 ) {
unset( $rates['flat_rate:8'] );
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
Please let me know if you find any issues.

Issue allow only one product in WooCommerce cart

We have a booking system which should allow only one product in the cart (when customers adds next product, previous one should be deleted from the cart).
Until today we have been using following code:
add_filter( 'woocommerce_add_to_cart_validation', 'b_only_one_in_cart', 99, 2 );
function b_only_one_in_cart( $passed, $added_product_id ) {
wc_empty_cart();
return $passed;
}
But it ceased to work (and I can't find why). Has something changed in the recent version of WooCommerce? How can I get it to work again?
You could use WC()->cart->empty_cart(); instead
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// When NOT empty
if ( ! WC()->cart->is_empty() ) {
// Empties the cart and optionally the persistent cart too.
WC()->cart->empty_cart();
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
If the above does not work for some reason, you can also apply it in the following way: (Solution for PHP 7.3 and up)
// Used to calculate totals
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Get cart
$get_cart = $cart->get_cart();
// Solution for PHP 7.3 and up
foreach ( $get_cart as $cart_item_key => $cart_item ) {
// NOT last element
if ( $cart_item_key !== array_key_last( $get_cart ) ) {
// Remove a cart item
$cart->remove_cart_item( $cart_item_key );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );

Make a filter product specific

I have a woocommerce installation and have being trying to force the cart to return a fixed value regardless of the quantity. I have finally found the right filter to do this.
add_filter('woocommerce_cart_subtotal','subtotalchanger',0);
function subtotalchanger($subtotal){
$my_fixed_subtotal = 1.65;
return $my_fixed_subtotal;
}
But when trying to target the product concerned the filter will not work.
add_filter('woocommerce_cart_subtotal','subtotalchanger',0);
function subtotalchanger($subtotal){
if (is_single('15455')){
$my_fixed_subtotal = 1.65;
return $my_fixed_subtotal;
}
}
what am I doing wrong here?
Do you mean this?
function subtotalchanger($subtotal, $compound, $cart ) {
$cart = WC()->cart->get_cart();
foreach( $cart as $cart_item ) {
$product = wc_get_product( $cart_item['product_id'] );
// Get product id
$product_id = $product->get_id();
if ( $product_id == 15455 ) {
$subtotal = 1.65;
}
}
return $subtotal;
}
add_filter( 'woocommerce_cart_subtotal', 'subtotalchanger', 10, 3 );

woocommerce add custom price while add to cart

Hi I need to add an extra price to product price while add to cart.
http://url/warenkorb/?add-to-cart=1539&added_price=5.00
I have used the code following code to achive this.
add_filter( 'woocommerce_add_cart_item', 'c_other_options_add_cart_item', 20, 1 );
function c_other_options_add_cart_item( $cart_item ) {
if (isset($cart_item['_other_options'])) :
if( isset($cart_item['_other_options']['product-price']) )
$extra_cost = floatval($cart_item['_other_options']['product-price']);
$cart_item['data']->adjust_price( $extra_cost );
// here the real adjustment is going on...
endif;
return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', c_other_options_add_cart_item_data', 10, 2 );
function c_other_options_add_cart_item_data($cart_item_meta, $product_id){
global $woocommerce;
$product = new WC_Product( $product_id);
$price = $product->price;
if(empty($cart_item_meta['_other_options']))
$cart_item_meta['_other_options'] = array();
$cart_item_meta['_other_options']['product-price'] = esc_attr($_REQUEST['price']) - $price;
return $cart_item_meta;
}
It shows the modified price on add to cart page but not in the cart/checkout page. Please Help me to achieve this. Thanks in advance.
You have to use woocommerce_before_calculate_totals hook for this purpose,
like this
function calculate_extra_fee( $cart_object ) {
/* Extra fee */
$additionalPrice = 100;
foreach ( $cart_object->cart_contents as $key => $value ) {
/* if you want to add extra fee for particular product, otherwise remove the if condition */
if( $value['product_id'] == 100) {
$quantity = intval( $value['quantity'] );
$orgPrice = intval( $value['data']->price );
$value['data']->price = ( ( $orgPrice + $additionalPrice ) * $quantity );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_extra_fee', 1, 1 );

Need Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another 1 is added then it should remove the previous 1

I think this code should work but not exactly sure where to place it. Everywhere I have tried has failed so far...
add_action('init', 'woocommerce_clear_cart');
function woocommerce_clear_cart() {
global $woocommerce, $post, $wpdb;
$url = explode('/', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$slug=$url[4];
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name = '$slug'");
if ($postid){
if ($postid == PRODUCTID1 || $postid == PRODUCTID2){
$woocommerce->cart->empty_cart();
}
}
}
Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart.
That is how I use it:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
// Do nothing with the data and return
return $cart_item_data;
}
Based on the accepted answer and the latest Woo version 2.5.1 I updated the function to be slightly cleaner using the code woo uses in class-wc-checkout.php to clear the cart
add_filter( 'woocommerce_add_cart_item_data', '_empty_cart' );
function _empty_cart( $cart_item_data ) {
WC()->cart->empty_cart();
return $cart_item_data;
}
There is a filter/hook that runs before an item is added to the cart as each product goes through validation before it is added.
So when validating a product, we can check if the item if there are already items in the cart and clears those (if the current item is able to be added) and adds an error message.
/**
* When an item is added to the cart, remove other products
*/
function so_27030769_maybe_empty_cart( $valid, $product_id, $quantity ) {
if( ! empty ( WC()->cart->get_cart() ) && $valid ){
WC()->cart->empty_cart();
wc_add_notice( 'Whoa hold up. You can only have 1 item in your cart', 'error' );
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_27030769_maybe_empty_cart', 10, 3 );
This worked like a charm for me, removes the previous product and adds the new one with the new product configuration. Cheers
Update: For WooCommerce 3.0.X
function check_if_cart_has_product( $valid, $product_id, $quantity ) {
if(!empty(WC()->cart->get_cart()) && $valid){
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if( $product_id == $_product->get_id() ) {
unset(WC()->cart->cart_contents[$cart_item_key]);
}
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
For WooCommerce version less than 3.0.X
function check_if_cart_has_product( $valid, $product_id, $quantity ) {
if(!empty(WC()->cart->get_cart()) && $valid){
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if( $product_id == $_product->id ) {
unset(WC()->cart->cart_contents[$cart_item_key]);
}
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
You have two options:
WooCommerce Min/Max Quantities extension
The following code added to your functions.php theme file
add_filter ( 'woocommerce_before_cart' , 'allow_single_quantity_in_cart' );
function allow_single_quantity_in_cart() {
global $woocommerce;
$cart_contents = $woocommerce->cart->get_cart();
$keys = array_keys ( $cart_contents );
foreach ( $keys as $key ) {
$woocommerce->cart->set_quantity ( $key, 1, true );
}
}
Don't add functions directly to your commerce files...you'll lose all your code when you update.
User functions should always be hooked through the functions.php of your theme.
Add this to your child-themes functions.php (tested in 2022, requires PHP 7 or higher):
add_filter('woocommerce_add_cart_item_data', function($cart_data) {
wc_empty_cart();
return $cart_data;
}, 99);
The "woocommerce_add_cart_item_data" filter fires every time a new item is added to the cart. We use this chance to call "wc_empty_cart" which empties the cart and optionally the persistent cart too. The new items is therefore alone in the cart.
Try this,
For removing the all products from the cart and adding the last added one,
//For removing all the items from the cart
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,$qty);
class file is wp-content/plugins/woocommerce/classes/class-wc-cart.php.
You can add the above code on the add to cart function in functions.php.
Hope its works..
Eu coloco na function.php do tema, o que faço ou no woocomerce
function check_if_cart_has_product( $valid, $product_id, $quantity ) {
if(!empty(WC()->cart->get_cart()) && $valid){
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if( $product_id == $_product->id ) {
wc_add_notice( 'The product is already in cart', 'error' );
return false;
}
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
On WordPress 5.6.1. no need to add a custom filter or write code there is an option to limit one product add to the cart.

Resources