Woocommerce: Run PHP function on cart update [duplicate] - php

This question already has an answer here:
Display message based on cart items count in WooCommerce cart
(1 answer)
Closed 3 years ago.
I want to display a message on my WooCommerce Cart Page, that tells my customers, how much they need to purchase to get a free gift.
I already got the following code which works, but I have one problem.
When customers update their cart or the quantity the following code does not update (because the page does not reload).
<?php $e_cart = WC()->cart->cart_contents_total * 1.25;?>
<?php $e_cart_remaining = 300 - $e_cart; ?>
<?php
if ( $e_cart < 300 ) {
echo "Get a free gift, when you purchase for ${e_cart_remaining} more.";
}?>
So the problem is, that if a customers has goods for 250 in his cart the message will say: "Purchase for 50 more to get a free gift". (Because you will get a free gift at 300). But if they change the quantity of one of the products the text still says 50. (Because the page have not updated)
How do i trigger this script or block of code every time the cart is updated?
Thank you very much.

To display a custom message on cart page based on cart amount, use the following:
// On cart page only
add_action( 'woocommerce_check_cart_items', 'custom_total_item_quantity_message' );
function custom_total_item_quantity_message() {
$e_cart = WC()->cart->cart_contents_total * 1.25;
$e_cart_remaining = 300 - $e_cart;
if( is_cart() && $e_cart < 300 ){
wc_print_notice( sprintf( __("Get a free gift, when you purchase for %s more.", "woocommerce"), $e_cart_remaining ), 'notice' );
}
}
Code goes in function.php file of your active child theme (or active theme).

Related

Custom add a shipping price in Woocommerce programmatically [duplicate]

This question already has an answer here:
Shipping cost based on cart total weight in Woocommerce 3
(1 answer)
Closed 2 years ago.
I'm trying to custom code the shopping cart in Woocommerce by changing the price of the delivery when a condition is met.
For example, if the product weighs 25kg, then simply add another price on top.
Here's my code in functions.php but it doesn't seem to work when i refresh the shopping cart.
$chosen_shipping_state = WC()->customer->get_shipping_postcode();
$chosen_state = $chosen_shipping_state;
// Get the selected shipping price
$chosen_shipping_method_price = WC()->session->get('cart_totals')['shipping_total'];
if ($cartweight >= 25 && $cartweight <= 50) {
WC()->session->set('shipping_total', '100');
do_action( 'woocommerce_cart_updated' );
}
So the current price of the selected courier is $5.50.
If the product weighs over 25 kgs, how do I made the courier price set to $11 and the shopping cart automatically refreshes with this amount?
First, you must choose shipping method ID.
Second, You need to put this code on your functions.php file inside your active theme directory. If your code is not working, please try to clear WooCommerce transient. In order to clear your WooCommerce transient, you can go to WooCommerce -> Status. Then click on Tools tab and you will see WooCommerce Transients. Click on the Clear Transients button.
add_filter( 'woocommerce_package_rates', 'override_ups_rates' );
function override_ups_rates( $rates ) {
foreach( $rates as $rate_key => $rate ){
// Check if the shipping method ID is UPS for example
if( ($rate->method_id == 'flexible_shipping_ups') ) {
// Set cost to zero
$rates[$rate_key]->cost = 5.50;
}
}
return $rates;
}

Show selected out of stock products In Woocommerce

I'm trying to find a solution to a client demand, without success. She's asking me how to show a selected number of out of stock products on her online store. By default, the Woocommerce setting is set to "hide out of stock products", but she wants to select some of her products and show them (even with 0 stock, because she wants to tell their customers that those few products will be available soon -there is a text for this-).
We have tried with a very simple snippet using the hook woocommerce_product_is_visible that we thought it would work, but there is something that we are missing...
This is de code:
// [WooCommerce] Show some out of stock products even the hide option is active
add_filter( 'woocommerce_product_is_visible', 'keep_showing_specific_out_of_stock_product_list', 10, 2 );
function keep_showing_specific_out_of_stock_product_list( $visible, $product_ID ){
$product_list = array( 18013, 18050 ); // Insert the products IDs that want to show
return in_array( $product_ID, $product_list )? true : $visible;
}
Any help is appreciated.
Why you don't simply use a Woocommerce shortcode like:
1) In the Wordpress text editor of a page or a post (or in a widget):
[products ids="18013,18050"]
2) In any PHP code file:
echo do_shortcode( "[products ids='18013,18050']" );
The products out of stock are displayed just like in this real example:

When price is 0 change add to cart button to "request quote" [duplicate]

This question already has answers here:
Replace product zero displayed price with a custom text in Woocommerce 3
(1 answer)
Customize "Add to cart" button for a specific product category in WooCommerce
(2 answers)
Closed 4 years ago.
I have a product X in several sizes (added as variation products of the main product X). For small sizes the price is available and customers can shop it online. However, for large sizes of this product X, it is not shopable online. Therefore for some variations of this product X I would like to remove the add to cart button and change it to a button who goes to my "request a quote" page.
My idea was that if I set the variable product price to 0 that the add to cart button goes away and the "request a quote" button appears.
Any ideas on how to do this in woocommerce (php)?
put this function in your function.php
add_filter('woocommerce_get_price_html', 'requestQuote', 10, 2);
function requestQuote($price, $product) {
if ( $price == wc_price( 0.00 ) ){
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_add_to_cart', 30 );
return 'Request Quote';
}
else{
return $price;}
}
you just need to make some condition with if function
$price = 2000;
$response = 'Add To Cart;
if(size = XL)
{
$price = 0;
$response = "You can Request another Size";
}

Allow add to cart for specific products based on cart total in WooCommerce

In woocommerce, I am trying to find a way to only allow a product to be added a to cart only when a specific cart total amount is reached.
Example: We want to sell a bumper sticker for $1, but only if a user already has $25 worth of other products already in the cart. This is similar to Amazon's "add on" feature. However I can't find a similar WooCommerce plugin or function.
I have tried yet some code without success… Any help will be appreciated.
Can be done with a custom function hooked in woocommerce_add_to_cart_validation filter hook, where you will define:
a product Id (or multiple product Ids).
the threshold cart amount to be reached.
It will avoid for those defined products to be added to cart (displaying a custom notice) until that specific cart amount is reached.
The code:
add_filter( 'woocommerce_add_to_cart_validation', 'wc_add_on_feature', 20, 3 );
function wc_add_on_feature( $passed, $product_id, $quantity ) {
// HERE define one or many products IDs in this array
$products_ids = array( 37, 27 );
// HERE define the minimal cart amount that need to be reached
$amount_threshold = 25;
// Total amount of items in the cart after discounts
$cart_amount = WC()->cart->get_cart_contents_total();
// The condition
if( $cart_amount < $amount_threshold && in_array( $product_id, $products_ids ) ){
$passed = false;
$text_notice = __( "Cart amount need to be up to $25 in order to add this product", "woocommerce" );
wc_add_notice( $text_notice, 'error' );
}
return $passed;
}
Code goes in function.php file of your active child theme (active theme).
Tested and works.

Remove the stock quantity from WooCommerce cart error messages

Iin WooCommerce, I've set woocommerce->settings->products->inventory->stock display format to "Never show quantity remaining in stock".
However if a customer ads a product to the cart, continues to cart or checkout page and enter a value higher than we have in stock they get this error message:
Sorry, we do not have enough "{product_name}" in stock to fulfill your order ({available_stock_amount} in stock). Please edit your cart and try again. We apologize for any inconvenience caused.
What filter can I use to edit this output? I don't want it to show (absolutely anywhere on the front end shop) the actual available stock amount.
I've found that this is handled in a function (check_cart_item_stock) in, [root]->wp-content->plugins->woocommerce->includes->class-wc-cart.php on line 491:
if ( ! $product->has_enough_stock( $product_qty_in_cart[ $product->get_stock_managed_by_id() ] ) ) {
/* translators: 1: product name 2: quantity in stock */
$error->add( 'out-of-stock', sprintf( __( 'Sorry, we do not have enough "%1$s" in stock to fulfill your order (%2$s in stock). Please edit your cart and try again. We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name(), wc_format_stock_quantity_for_display( $product->get_stock_quantity(), $product ) ) );
return $error;
}
So what I want to filter out is the "(%2$s in stock)" part. But I can't find any filter for this.
This messages displayed are located in WC_Cart class source code at line 493 and 522 …
What you can try is to replace the text by your custom text version in this function hooked in WordPress gettex filter hook:
add_filter( 'gettext', 'wc_replacing_cart_stock_notices_texts', 50, 3 );
function wc_replacing_cart_stock_notices_texts( $replacement_text, $source_text, $domain ) {
// Here the sub string to search
$substring_to_search = 'Sorry, we do not have enough';
// The text message replacement
if( strpos( $source_text, $substring_to_search ) ) {
// define here your replacement text
$replacement_text = __( 'Sorry, we do not have enough products in stock to fulfill your order…', $domain );
}
return $replacement_text;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This should works (unstested)…
Thank you #LoicTheAztec for your reply, but I actually found a filter for this after all, woocommerce_add_error
So my final filter (in functions.php) is this:
function remove_stock_info_error($error){
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $item) {
$product_id = isset($item['variation_id']) ? $item['variation_id'] : $item['product_id'];
$product = new \WC_Product_Factory();
$product = $product->get_product($product_id);
if ($item['quantity'] > $product->get_stock_quantity()){
$name = $product->get_name();
$error = 'Sorry, we do not have enough "'.$name.'" in stock to fulfill your order. Please edit your cart and try again. We apologize for any inconvenience caused.';
return $error;
}
}
}add_filter( 'woocommerce_add_error', 'remove_stock_info_error' );
This should resolve it across the board.
NOTE! I also found that the input boxes have a max attribut, which in turn means that anyone can still see the actual total available amount (by either simply using the built in increment (which will stop when reaching max value) or just enter to high of a value, click update cart and you will get a notice that the amount has to be equal to or less than X (max value)).
To combat this I added a simple JS in my pre-existing "woo-xtra.js":
var qty = $('form.woocommerce-cart-form').find('input.qty');
// Reset max value for quantity input box to hide real stock
qty.attr('max', '');
This way there is no max value, but the user will still get the error (if over the limit) from above :)
I.e. Problem solved

Categories