skip to Main Content

How to change a WooCommerce add to cart button in Product List loop but depending on the product type, like for example:

  1. For products with Variations I want a text in add to cart button to: "Show product"
  2. For Simple prodcuts "Show product"
  3. For products Out of stock: "Unavailable"

I tried with below code but doesn’t work:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product  ) {
    $button_text = __( "Out of stock", "woocommerce" );
    return '<a class="view-product" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    if( ! $product->managing_stock() && ! $product->is_in_stock() ) {
        return $button;
    }
    if( $product->is_type( 'variable' ) ) return $button;
}

2

Answers


  1. Try the following instead:

    add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
    function replace_loop_add_to_cart_button( $button, $product  ) {
        // Out of stock products
        if( ! $product->is_in_stock() ) {
            $button_text = __( "Unavailable", "woocommerce" );
        }
        // Simple and Variable products
        elseif( $product->is_type( 'simple' ) || $product->is_type( 'variable' ) ) {
            $button_text = __( "Show product", "woocommerce" );
        } 
        // Other product types
        else {
            $button_text = add_to_cart_text(); 
        }
        
        return '<a class="view-product button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should work

    Login or Signup to reply.
  2. To change woocommerce Book Now button I installed this plugin https://wordpress.org/plugins/button-customizer-for-woocommerce/ and added 2 filters to functions.php and finally, it works

     add_filter( 'woocommerce_booking_single_check_availability_text', 'wooninja_booking_check_availability_text' );
    function wooninja_booking_check_availability_text() {
        return "your text";
    } 
     add_filter( 'woocommerce_booking_single_add_to_cart_text', 'wooninja_woocommerce_booking_single_add_to_cart_text' );
    function wooninja_woocommerce_booking_single_add_to_cart_text() {
        return "your text";
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search