Search code examples
phpwordpresswoocommerceproductarchive

Change add to cart button and text based on WooCommerce product type


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;
}

Solution

  • 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