Home > front end >  Change WooCommerce "out of stock" message based on category in OceanWP
Change WooCommerce "out of stock" message based on category in OceanWP

Time:11-25

I want to change the out of stock message in WooCommerce for one category only on the single product page and shop archive pages.

I am using OceanWP theme

This is what I have so far, which works, but I need to add the "if" statement for category.

/** 
*This changes the out of stock text on the item in oceanwp theme product gallery  
*/ 
function my_woo_outofstock_text( $text ) {
    $text = __( 'Sold', 'oceanwp' );
    return $text;
}
add_filter( 'ocean_woo_outofstock_text', 'my_woo_outofstock_text', 20 );

Here is my code attempt, based on this similar question here, but it only works on the single product page. Any advice?

function my_woo_outofstock_text( $text, $product ) {
    $specific_categories = array( 'original-paintings' );
    
    if ( ! $product->is_in_stock() && has_term( $specific_categories, 'product_cat', $product->get_id() ) ) {
         $text = __( 'Sold', 'oceanwp' );
    }
    else {
        $text = __( 'Unavailable', 'oceanwp' );
    }        
    
    return $text;
}
add_filter( 'ocean_woo_outofstock_text', 'my_woo_outofstock_text', 20 );

CodePudding user response:

The filter hook you are using only contains 1 argument, so $product is not part of it. If you still want to apply changes based on the $product for the shop archive pages, you should apply this globally.

So you get:

function my_woo_outofstock_text( $text ) {
    global $product;
    
    // Add categories. Multiple can be added, separated by a comma
    $specific_categories = array( 'original-paintings' );
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // NOT in stock & has term
        if ( ! $product->is_in_stock() && has_term( $specific_categories, 'product_cat', $product->get_id() ) ) {
            $text = __( 'Sold', 'oceanwp' );
        } else {
            $text = __( 'Unavailable', 'oceanwp' );
        }  
    }
    
    return $text;
}
add_filter( 'ocean_woo_outofstock_text', 'my_woo_outofstock_text', 20, 1 );

For the single product page you can use Custom "Out of stock" text based on product category in WooCommerce answer code.

  • Related