skip to Main Content

I am not very familiar with php, and I am trying to add a class to ‘Low stock’ in the snippet below.

What I am trying to achieve is making the Low Stock orange vis CSS in WooCommerce.


function change_stock_text( $availability, $_product ) {

    if ( $_product->is_in_stock() ) {

        if ( $_product->get_stock_quantity() < 3 ) {

            $qty                          = $_product->get_stock_quantity();
            $availability['availability'] = __( "Low stock", 'woocommerce' );
        }
    }

    return $availability;
}

2

Answers


  1. it’s been sometime since I worked with WooCommerce, so i am not sure if this will do the trick, but you can try:

    $availability['availability'] = __( "<em class='low_stock'>Low stock</em>", 'woocommerce' );
    

    This might work, otherwise there’s likely a hook for it.

    Login or Signup to reply.
    • add_filter() is missing
    • $availability contains [availability] & [class], you change the text, while you want to add a class
    • $qty is unused in your code
    • A class doesn’t have to be translatable, so using __() is not necessary

    To add a class to the already existing class with the if condition, use the woocommerce_get_availability_class filter hook instead

    // Availability class
    function filter_woocommerce_get_availability_class( $class, $product ) {
        // In stock
        if ( $product->is_in_stock() ) {
            // Stock quantity less then 3
            if ( $product->get_stock_quantity() < 3 ) {
                $class .= ' low-stock';
            }
        }
    
        return $class;
    }
    add_filter( 'woocommerce_get_availability_class', 'filter_woocommerce_get_availability_class', 10, 2 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search