Search code examples
phpwordpresswoocommerceproducthook-woocommerce

WooCommerce - Change "add to cart" button text to products with no price


I want to change the "add to cart" button text to "for more additional information" but i want the function to work only for products that didnt set any price at all.

so far i found those 2 snippets but i couldn't figure out how to combine them

  1. this code will change the price for products without a price to text:
function add_inquiry_link_instead_price( $price, $product ) {

    if ( '' === $product->get_price() || 0 == $product->get_price() ) {

        return '<span class="price_on_inquiry">TEXT TO CHANGE HERE</span>';

    }

    return $price;

}

add_filter( 'woocommerce_get_price_html', 'add_inquiry_link_instead_price', 100, 2 );

2.this code will change the "add to cart" button text to what i write

add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_product_add_to_cart_text' );  
function woocommerce_custom_product_add_to_cart_text() {
    return __( 'TEXT TO CHANGE HERE', 'woocommerce' );
}

Solution

  • add_filter('woocommerce_product_add_to_cart_text', 'woocommerce_custom_product_add_to_cart_text', 10, 2);
    
    function woocommerce_custom_product_add_to_cart_text($text, $product) {
    
        if ('' === $product->get_price() || 0 == $product->get_price()) {
            $text = __('TEXT TO CHANGE HERE', 'woocommerce');
        }
        return $text;
    }
    

    WooCommerce is passing the product with the corresponding product type add to cart text callback. See the sample from WooCommerce core for simple products below.

    /**
         * Get the add to cart button text.
         *
         * @return string
         */
        public function add_to_cart_text() {
            $text = $this->is_purchasable() && $this->is_in_stock() ? __( 'Add to cart', 'woocommerce' ) : __( 'Read more', 'woocommerce' );
    
            return apply_filters( 'woocommerce_product_add_to_cart_text', $text, $this );
        }