tinyiguanas
tinyiguanas

Reputation: 67

Exclude Custom WooCommerce availability text from specific products

I'm using the following php code to add a custom, global message on Woocommerce product pages next to the product availability text (In stock/Out of stock).

add_filter( 'woocommerce_get_availability_text', 'filter_product_availability_text', 10, 2 );
function filter_product_availability_text( $availability_text, $product ) {

    if( $product->is_in_stock() && $product->managing_stock() && 
    ! $product-> is_on_backorder( 1 ) && $product->get_stock_quantity() > 0 ) {
        $availability_text .= 'Free Shipping' . __("", "woocommerce");
    }
    return $availability_text;
}

The "Free Shipping" message is currently shown on all product pages. How could I exclude specific products from showing that custom availability message?

Upvotes: 1

Views: 278

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254448

Updated

By adding in your IF statement an array of product Ids to exclude as follows:

&& ! in_array( $product->get_id(), array(37, 45, 46, 58) )

So in your code:

add_filter( 'woocommerce_get_availability_text', 'filter_product_availability_text', 10, 2 );
function filter_product_availability_text( $availability_text, $product ) {
    if( $product->is_in_stock() && $product->managing_stock() 
    && ! $product->is_on_backorder( 1 ) && $product->get_stock_quantity() > 0 
    && ! in_array( $product->get_id(), array(37, 45, 46, 58) ) ) {
        $availability_text .= ' ' . __("Free Shipping", "woocommerce");
    }
    return $availability_text;
}

It should work.


Handling variable products

To handle variable products too, you can replace the code line:

&& ! in_array( $product->get_id(), array(37, 45, 46, 58) ) ) {

by the following code line:

&& ! array_intersect( array($product->get_id(), $product->get_parent_id()), array(37, 45, 46, 58) ) ) {

Upvotes: 2

Related Questions