Search code examples
phpwordpresswoocommerceproductstock

Stock status color badge in a custom shortcode for WooCommerce


In WooCommerce, I use the following code in my Theme Functions, functions.php:

function webis_stoc( $atts ){
   global $product;
   echo "<div class='stoc'>";
   $stoc=$product->stock_status;
   switch($stoc){
       case "onbackorder": echo "<span class='precomanda'; style='color:orange;'; >Precomanda</span>"; break;
      case "instock": echo "<span class='inStoc'; style='color:green;' >in stoc</span>"; break;
      case "outofstock": echo "<span class='farastoc'; style='color:red;' >Stoc epuizat</span>"; break;
      default : echo $stoc; break;
   }
   echo "</div>";
}
add_shortcode  ('webis_stoc','webis_stoc' ); 

The Issue I am having here is that the CSS for each case (3 cases) is not displaying, It's always green, no red or orange, even if it's in on backorder or out of stock, it's still green.
How can I solve this?

Here is the "onbackorder" that is supposed to be orange:

enter image description here

I tried to modify the colors with background-color , but it only changed the color of the text, and I want the full button to recolor.


Solution

  • There are some mistakes, errors and missing things in your code.

    Try the following revisited code instead (commented):

    add_shortcode  ('webis_stoc', 'webis_stoc' ); 
    function webis_stoc( $atts ){
        global $product;
        
        if( ! $product ) return; // exit if $product variable is not defined
        
        $stoc = $product->get_stock_status(); // Get product stock status
        
        $html = '<div class="stoc">';
       
        switch( $stoc ){
            case 'onbackorder': // 
                $html .= '<span class="precomanda"; style="color:orange;">Precomanda</span>'; 
                break;
            case 'outofstock': 
                $html .= '<span class="farastoc"; style="color:red;" >Stoc epuizat</span>'; 
                break;
            default: // 'instock' (default fallback)
                $html .= '<span class="inStoc"; style="color:green;" >in stoc</span>'; 
                break;
        }
        return $html . '</div>'; // For shortcodes, always return, never echo...
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.