Search code examples
phpwordpresswoocommercehook-woocommercestock

Replace Out of stock text with a button in WooCommerce


I want to replace the Out of stock text with a Contact us button.

I tried this code, but it doesn't seem to work for me.

add_action('woocommerce_after_shop_loop_item', 'themelocation_change_outofstock_to_contact_us', 1);
// for shop page 
function themelocation_change_outofstock_to_contact_us() {
  global $product;
  if (!$product->is_in_stock()) {
    remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
    remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart');
    //change the link to your contact us page
    echo '<a href="/contact"> Contact Us </a>';
  }
}
// for single page
add_filter('woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
function wcs_custom_get_availability($availability, $_product) {
  // Change In Stock Text
  if ($_product->is_in_stock()) {
    $availability['availability'] = __('Available!', 'woocommerce');
  }
  // Change Out of Stock Text
  if (!$_product->is_in_stock()) {
    $availability['availability'] = __('<a href="/contact"> Contact Us </a>', 'woocommerce');
  }
  return $availability;
}


Solution

  • add_filter('woocommerce_get_availability_text', 'woocommerce_get_availability_text', 10, 2);
    
    function woocommerce_get_availability_text($availability, $product){
    
        /*
        if ( ! $product->is_in_stock() ) {
            $availability = __('<a href="/contact"> Contact Us </a>', 'woocommerce');
        }
         * 
         */
    
        if($availability == 'Out of stock'){
            $availability = __('<a href="/contact"> Contact Us </a>', 'woocommerce');
        }
        return $availability;
    }
    

    Try below code for the specific message.

    add_filter( 'woocommerce_out_of_stock_message', 'woocommerce_get_availability_text_msg', 10, 1 );
    
    function woocommerce_get_availability_text_msg( $availability ) {
    
        return __( '<a href="/contact"> Contact Us </a>', 'woocommerce' );
    
    }