I add some custom stock status messages on WooCommerce with some PHP code like this :
//Ajoute "En stock" sous chaque produit
function show_stock() {
global $product;
if ( $product->managing_stock() ) { // if manage stock is enabled
if (( number_format($product->get_stock_quantity(),0,'','') > 0 ) && ( number_format($product->get_stock_quantity(),0,'','') < 100 )) { // if in stock
echo '<div class="remaining" style="color:green;">En stockk</div>';
} elseif (( number_format($product->get_stock_quantity(),0,'','') >= 100 ) && ( number_format($product->get_stock_quantity(),0,'','') < 1000 )) {
echo '<div class="remaining" style="color:#f2cd00;">Livraison sous 1 mois</div>';
} elseif (( number_format($product->get_stock_quantity(),0,'','') >= 1000 ) && ( number_format($product->get_stock_quantity(),0,'','') < 2000 )) {
echo '<div class="remaining" style="color:#f2cd00;">Livraison sous 7 jours</div>';
} elseif ( number_format($product->get_stock_quantity(),0,'','') < 1 ) {
echo '<div class="remaining" style="color:red;">Rupture</div>';
}
}
}
add_action('woocommerce_after_shop_loop_item','show_stock', 10);
add_action ('woocommerce_before_add_to_cart_form','show_stock');
And i apply this CSS rule for make disappear the default WooCoomerce stock message in my single product page and avoid double stock status messages.
p.stock{
display: none;
}
The Problem that i have is my PHP code not working anymore when stock = 0 and then my last conditional of php code isn’t apply (not showing my custom message “Rupture”).
And because i applied my CSS rule when my stock = 0 i have no stock status.
Then i would like to apply my CSS rule only when my stock > 0.
Or
Find way to make apply my last conditional php for stock < 1.
:'( thank you
3
Answers
OMG Thanks a lot 7uc1f3r and thanks to all for your reply and participation.
I tryed your code and it's work like a charm. I didn't know how to just replace the default stock status.
I just added CSS for the single procut page because the custom color was not taken just cause the different class (stock.custom-stock-color)
This is the final code adapted for my site:
***********************************************************PHP****************************************
************************CSS***********************
*****************************THANK YOU AGAING*******************************
i recomend refactoring your code because your “logic” is correct, but your semantic is no so god.
1 – define type for return
$product->get_stock_quantity()
2 – In php type number is equivalent to string too (because as dynamic type)
3 – Verify that
$product->get_stock_quantity()
return value when list has emptyThe following code shows how to change text & class, both on the Single product page + add html on the Shop/Category page
In this way you can adjust or add your custom availability text/class.
PHP: Add to
functions.php
CSS: Add to an external style sheet, your CSS theme file or via a plugin