WooCommerce Blocks: Change Read More Button on Out of Stock Products

Viewed 333

I'm trying to change the "Read More" button on the Homepage of my WooCommerce shop and I don't figure out how to do that. The homepage is using Gutenberg Blocks to show most popular products and when I have an out of stock product in there, instead of the "Shop now" button it is one that says "Read More". I want to change that "Read More" to "Out of stock".

What I did by now:

  1. Changed the "Read More" to "Out of Stock" on the shop page, using this code:
function change_loop_add_to_cart_button( $button, $product, $args = array() ) {
    if( !$product->is_in_stock() ){
        $button = '<a class="button disabled" style="color:#000;background-color:#fff;border: 1px solid #ddd;">'.__('Out of stock', 'woocommerce').'</a>';
    }
   return $button;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'change_loop_add_to_cart_button', 20, 3 );
  1. I've found that the Gutenberg Block can be filtered in functions.php using this code:
    add_filter( 'woocommerce_blocks_product_grid_item_html', 'bbloomer_remove_product_grid_block_badge', 9999, 3 );
 
function bbloomer_remove_product_grid_block_badge( $html, $data, $product ) {
   return "<li class=\"wc-block-grid__product\">
            <a href=\"{$data->permalink}\" class=\"wc-block-grid__product-link\">
               {$data->image}
               {$data->title}
            </a>
            {$data->price}
            {$data->rating}
            {$data->button}
         </li>";
}

What I don't know how to do is to include an If function in the 2nd code snippet to change {$data->button} with "Out of stock" text if the product is out of stock.

Thank you!

1 Answers

the correct filter you should use is "woocommerce_product_add_to_cart_text".

This should do the trick:

add_filter( 'woocommerce_product_add_to_cart_text', 'bbloomer_archive_custom_cart_button_text' );
 
function bbloomer_archive_custom_cart_button_text( $text ) {
   global $product;       
   if ( ! $product->is_in_stock() ) {           
      return 'Out of stock';
   } 
   return $text;
}

I got some inspiration from this post, which changes button text by product category, but code should be very similar

Related