Damien Kloot
Damien Kloot

Reputation: 17

Add CSS class for low stock products on single product page in WooCommerce

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;
}

Upvotes: 0

Views: 505

Answers (2)

7uc1f3r
7uc1f3r

Reputation: 29614

  • 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 );

Upvotes: 1

Victor Ivanov
Victor Ivanov

Reputation: 126

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.

Upvotes: 0

Related Questions