I need to set a threshold on a per product basis for stock inventory.
Example : If the product has a threshold of 10 and there's 10 or less in stock, the product shows the out of stock text. If the threshold is set at 10 but there's 15 in stock, 5 is shown in stock.
So what i need to do is offset the real inventory levels on a per product basis using a value.
This is the code i'm trying to get working
add_filter( 'woocommerce_get_availability', 'override_get_availability', 10, 2);
function override_get_availability( $availability, $product ) {
$stock_threshold = get_post_meta( $product->get_id(), '_stock_threshold', true );
if ( $product->managing_stock() && ! empty( $stock_threshold ) ) {
$availability['availability'] = $product->get_stock_quantity() - $stock_threshold;
return $availability;
}
}
This code doesn't show the Out of Stock text on the single product page if the inventory is calculated at 0 or less than zero.
Example : When the stock level is set at 2 and the offset is set at 2, it = 0 so should show Out of Stock but doesn't.
I think this gets you some of the way there;
add_filter( 'woocommerce_get_availability', 'override_get_availability', 10, 2);
function override_get_availability( $availability, $product ) {
$stock_threshold = $product->get_low_stock_amount();
$stock_quantity = $product->get_stock_quantity();
if ( $product->managing_stock() && !empty($stock_threshold) ) {
$avail_stock = ($stock_quantity - $stock_threshold);
if ($avail_stock <= 0){
$availability['availability'] = __('Out of Stock', 'woocommerce');
}
return $availability;
}
}
Basically, we're getting the low stock amount (threshold) and subtracting the stock quantity. If it's 0 or less, then set the availability to Out of Stock.
This works without a problem.
However if the product has 15 in stock and the threshold at 10, it still shows 15 as the out of stock is NOT 0.
I think the best approach is a combination of the above, and then shortcode to display the quantity minus the threshold rather than using the code inside WooCommerce.
Maybe someone else can build off what I have posted above as I couldn't get the quantity number to reduce on products NOT out of stock.
Related
I am using a function to put my entire store on sale for 15% off. It works great but it changes all the pricing the the loops and the product page just to the new 15% off price. How can I set the sale price but also show the regular price too so I can then cross out the regular price with CSS.
add_filter('woocommerce_product_get_price', 'assign_tier_pricing', 90, 2 );
add_filter('woocommerce_product_get_regular_price', 'assign_tier_pricing', 90, 2 );
function assign_tier_pricing( $price, $product ) {
if ( $product->is_type('simple') ) {
$price *= 0.85; // Set all prices for simple products to 50% off.
}
return $price;
}
I would like to also return the regular price in a span so I can style it and cross it out so customers can see the normal price along with the sale price
So also return <span class="regular-price">Display regular price</span> then the new sale price right next to it.
Use is_on_sale() to check https://woocommerce.github.io/code-reference/classes/WC-Product.html#method_is_on_sale
if ( $product->is_type('simple') && is_on_sale () )
or
if ( $product->is_type('simple') && ! is_on_sale () )
For ! Not on sale
Right now, my shop only displays only 2 badges on my shop page. Special Offer and out of stock. I would also want to include stock quantity below 10 and Allow for back order. I have looked at multiple plugins as well as php code, but nothing seems to work. What I want to do is display "Only {QTY} Is Available" is the stock drops below 10 and if it is 0 then "available on back order". Website is built in WooCommerce and WordPress
I would like these messages to replace the special offer badge if these conditions are met. I have attached a screenshot below:-
Any assistance is greatly appriciated
There are in fact two parts to your question: how to change the stock availability text and how to remove the sale badge, when some criteria on the product stock level is met.
Changing the stock availability text should be easily achieved by hooking in the woocommerce_get_availability filter. Get the product stock quantity and amend the text accordingly. E.g.:
add_filter( 'woocommerce_get_availability', 'custom_override_get_availability', 10, 2 );
function custom_override_get_availability( $availability, $_product ) {
$stock_quantity = $_product->get_stock_quantity();
if ( 0 === $stock_quantity ) {
$availability['availability'] = 'Available on backorder';
} elseif ( $stock_quantity < 10 ) {
$availability['availability'] = sprintf( 'Only %s available', $stock_quantity );
} else {
$availability['availability'] = sprintf( '%s left in stock', $stock_quantity );
}
return $availability;
}
As for removing the sale badge, I think the plugin you're using provides templates that can be overridden. Have a look in the Views folder, you should find the sale-flash.php templates. You can then override those templates in your theme and apply a similar logic, as you have access to the product. E.g. this shows the sale badge only when the product is on sale and the stock quantity is greater than or equal to 10:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
global $post, $product;
?>
<?php if ( $product->is_on_sale() && $product->get_stock_quantity() >= 10 ) : ?>
<?php echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale wdr-onsale">' . esc_html__( 'Sale!', 'woocommerce' ) . '</span>', $post, $product ); ?>
<?php endif;
Although I'm not really sure if you want to remove the sale badge when the product stock quantity is less than 10.
I have one little problem that dont know how to fix myself. I want to use this logic into my Woocommerce store just for one product.
I have use link like this to autmatically apply coupon code and add to cart:
https://testsite.com/checkout/?add-to-cart=Product_ID&quantity=1&coupon=Coupon_Code
and this seems to work, when quantity is 1. But i want discount (30%) that is automatically placed when click on direct link from before, to make dynamic, for ex:
Increase quantity to 2 in cart page, and coupon automatically to calculate 2 x 30$ = 60$ discount,
buy 3 from same product, and calculate 3 X 30$ = 90$ coupon discount
and so on..
I searched, and found this usefull thread, but there situation is little different then mine.
How can I make to have a specific coupon? Some advice or start point. Thanks
This is possible with that 2 steps:
1) Add a unique coupon with:
In General settings > Type = Fixed Product discount
In General settings > Amount = 30
In Usage restrictions > Products ==> set your desired product(s)
2) Add this code (where you will set your coupon code in the function (in lowercase)):
add_filter( 'woocommerce_coupon_get_discount_amount', 'custom_coupon_get_discount_amount', 10, 5 );
function custom_coupon_get_discount_amount( $rounded_discount, $discounting_amount, $cart_item, $single, $coupon ){
## ---- Your settings ---- ##
// Related coupons codes to be defined in this array (you can set many)
$coupon_codes = array('30perqty');
## ------ The code ------- ##
if ( $coupon->is_type('fixed_product') && in_array( $coupon->get_code(), $coupon_codes ) && $cart_item['quantity'] > 1 ) {
if( in_array( $cart_item['product_id'], $coupon->get_product_ids() ) ){
$discount = (float) $coupon->get_amount() * (int) $cart_item['quantity'];
$round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
}
}
return $rounded_discount;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I am a beginner trying to learn Wordpress and have a variable product with prices:
cod Rs 250
online Rs 200
I want to use the minimum price in my themes functions.php.
How will I be able to fetch or get the minimum value?
I want to use in the below code :
function filter_gateways($gateways){
$payment_NAME = 'cod'; //
$min_variation_price = ''; <--------------- minimum variation price
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) {
// 20 is the ID of the category for which we want to remove the payment gateway
if($term->term_id == $min_variation_price){
unset($gateways[$payment_NAME]);
// If you want to remove another payment gateway, add it here i.e. unset($gateways['cod']);
break;
}
break;
}
}
return $gateways;
}
To get the minimum variation active price in WooCommerce from a WC_Product_Variable object:
$variation_min_price = $product->get_variation_price();
It seems that you are trying here to unset 'cod' payment gateway when a cart item min variation price is matching with his product category ID.
Using the WordPress conditional function has_term() will really simplify your code (it accepts term Ids, term slugs or term names for any taxonomy (as 'product_cat' here for product categories).
I suppose that your function is hooked in woocommerce_available_payment_gateways filter hook…
I made some changes in your code as it's a bit outdated and with some errors:
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {
// Not in backend (admin)
if( is_admin() )
return $available_gateways;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Get the WC_Product object
$product = wc_get_product($cart_item['product_id']);
// Only for variable products
if($product->is_type('variable')){
// Get the Variation "min" price
$variation_min_price = $product->get_variation_price();
// If the product category match with the variation 'min" price
if( has_term( $variation_min_price, 'product_cat', $cart_item['product_id'] ) ){
// Cash on delivery (cod) payment gateway
unset($available_gateways['cod']); // unset 'cod'
break; // stop the loop
}
}
}
return $available_gateways;
}
Code goes in functions.php file of your active child theme (or theme) or also in any plugin file.
This should work (but I can't really test it as it's very specific regarding the product categories ID and the min variation prices)…
All related price methods for variable product type:
// All prices: multidimensional array with all variation prices (including active prices, regular prices and sale prices).
$prices = $product->get_variation_prices();
$prices_for_display = $product->get_variation_prices( true ); // For display
// The min or max active price.
$min_price = $product->get_variation_price(); // Min active price
$min_price_for_display = $product->get_variation_price('min', true); // Min active price for display
$max_price = $product->get_variation_price('max'); // Max active price
$max_price_for_display = $product->get_variation_price('max', true); // Max active price for display
// The min or max regular price.
$min_price = $product->get_variation_regular_price(); // Min regular price
$min_price_for_display = $product->get_variation_regular_price('min', true); // Min regular price for display
$max_price = $product->get_variation_regular_price('max'); // Max regular price
$max_price_for_display = $product->get_variation_regular_price('max', true); // Max regular price for display
// The min or max sale price.
$min_price = $product->get_variation_sale_price(); // Min sale price
$min_price_for_display = $product->get_variation_sale_price('min', true); // Min sale price for display
$max_price = $product->get_variation_sale_price('max'); // Max sale price
$max_price_for_display = $product->get_variation_sale_price('max', true); // Max sale price for display
Related answers:
Disable WooCommerce Payment methods if cart item quantity limit is reached
I think you are looking for that :
add_filter( 'woocommerce_variable_sale_price_html', 'get_min_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'get_min_variation_price_format', 10, 2 );
function get_min_variation_price_format( $price, $product ) {
$min_variation_price = $product->get_variation_regular_price( 'min');
return wc_price($min_variation_price);
}
I'm in a unique situation with my Woocommerce site.
I need to add a packaging fee, which will be somewhat similar to a handling fee.
Unfortunately, it's not as simple as adding a $5.00 handling fee to every order.
Since I sell wood products based on their measurements (width x height), the packaging fees are based on the total square footage for items. And they can differ depending on the category of the items, as well.
I've done a ton of research and I can't find a plugin to handle this situation.
To add to the complexity, there's a whole table that would need to be created. For example, if items from one category have a total square footage between 1-10, then the packaging fee will be $10. If total sq ftg is between 11-20, then it'll be $20.
How can I do to achieve that?
Thanks
Updated: Added WooCommerce 3+ compatibility
This is possible and easy with the add_fee() method in the woocommerce_cart_calculate_fees hook. Here is a simple usage example for simple products, with 2 categories and based on the product dimensions measurement calculations for each item of the cart. Its also possible for other product types.
Here is the example code (That you will need to customize for your own case):
add_action( 'woocommerce_cart_calculate_fees','custom_applied_fee', 10, 1 );
function custom_applied_fee( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be an ID, a slug or the name… or an array of this)
$category1 = 'plain';
$category2 = 'plywood';
// variables initialisation
$fee = 0;
$coef = 1;
// Iterating through each cart item
foreach( $cart_object->get_cart() as $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
$product = $cart_item['data']; // Get the product object
// Get the dimentions of the product
$height = $product->get_height();
$width = $product->get_width();
// $length = $product->get_length();
// Initialising variables (in the loop)
$cat1 = false; $cat2 = false;
// Detecting the product category and defining the category coeficient to change price (for example)
// Set here for each category the modification calculation rules…
if( has_term( $category1, 'product_cat', $cart_item['product_id']) )
$coef = 1.15;
if( has_term( $category2, 'product_cat', $cart_item['product_id']) )
$coef = 1.3;
// ## CALCULATIONS ## (Make here your conditional calculations)
$dimention = $height * $with;
if($dimention <= 10){
$fee += 10 * $coef;
} elseif($dimention > 10 && $dimention <= 20){
$fee += 20 * $coef;
} elseif($dimention > 20){
$fee += 30 * $coef;
}
}
// Set here the displayed fee text
$fee_text = __( 'Packaging fee', 'woocommerce' );
// Adding the fee
if ( $fee > 0 )
WC()->cart->add_fee( $fee_text, $fee, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
You will have to set your own categories with the related changes calculations for each category. You will get a non detailed general output fee calculated taking into account each item in the cart.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
The code is tested and fully functional.
Related Answers:
Discount for Certain Category Based on Total Number of Products
Cart discount for a product category based on quantity calculations