Skip to content
Advertisement

Custom “Out of stock” text based on product category in WooCommerce

Every out of stock product says “Out of Stock”

There are plenty of functions.php scripts that overwrite the text but I am only trying to overwrite the text specific to “Category A” or if I know the category “id” number, that could work too.

I found this script but it allows you to modify the txt per product id only.

add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 10, 2);       
function wcs_custom_get_availability( $availability, $_product ) { 
    // custom 
    if ( $_product->is_in_stock() && $_product->get_id() == '6498' ) {
        $availability['availability'] = sprintf( __('✔️ Available but low in stock | 30-day No Questions Asked Money-Back Guarantee Applies', 'woocommerce'), $_product->get_stock_quantity());
    }

    // Out of stock
    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('Sorry, All sold out!', 'woocommerce');
    }

    return $availability;
}

How can I further adapt this script taking into account the category?

Advertisement

Answer

To check for product category you can use has_term()

has_term( string|int|array $term = '', string $taxonomy = '', int|WP_Post $post = null )

Checks if the current post has any of given terms.


So you get:

function filter_woocommerce_get_availability( $availability, $product ) {
    // Specific categories
    $specific_categories = array( 'Categorie-A', 'categorie-1' );
    
    // Out of stock and has certain category     
    if ( ! $product->is_in_stock() && has_term( $specific_categories, 'product_cat', $product->get_id() ) ) {
        $availability['availability'] = __('My custom text', 'woocommerce' );
    }

    return $availability;
}
add_filter( 'woocommerce_get_availability', 'filter_woocommerce_get_availability', 10, 2 );
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement