N. Winton
N. Winton

Reputation: 55

"Add to Cart" functionality instead of "Select Options" button behavior for variable products

Woocommerce has two button types in the product loop


My setting:

All Woocommerce products are configured as simple products and subscription products at the same time using the following plugins

Now the buttons on all products change from "add to cart" to “select options”. That is Woocommerce default behavior.


My Question:

How can I keep the "add to cart" button and its functionality of adding the simple product to cart despite having a variable product?

Logic behind it: Users are given the opportunity to make a choice on checkout and therefore add to cart functionality instead of redirect to single product page for making a choice is desired.

Upvotes: 3

Views: 8568

Answers (2)

7uc1f3r
7uc1f3r

Reputation: 29640

You could use: (Explanation via comment tags added in the code)

function filter_woocommerce_loop_add_to_cart_link( $args, $product ) {
    // Shop page & product type = simple
    if ( is_shop() && $product->product_type === 'simple' ) {
        // Get product ID, sku & add to cart url
        $product_id = $product->get_id();
        $product_sku = $product->get_sku();
        $product_url = $product->add_to_cart_url();

        // Quantity & text
        $quantity = isset( $args['quantity'] ) ? $args['quantity'] : 1;
        $text = $product->add_to_cart_text();

        $args = '<a rel="nofollow" href="' . $product_url . '" data-quantity="' . $quantity . '" data-product_id="' . $product_id . '" data-product_sku="' . $product_sku . '" class="button product_type_simple add_to_cart_button ajax_add_to_cart add-to-cart" aria-label="Add to cart"><em>' . $text . '</em></a>';
    }
    
    return $args; 
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'filter_woocommerce_loop_add_to_cart_link', 10, 2 );

Upvotes: 3

N. Winton
N. Winton

Reputation: 55

function filter_woocommerce_loop_add_to_cart_link( $link, $product ) {

    if ( is_shop() && $product->product_type === 'simple' ) {
        $product_id = $product->get_id();
        $product_sku = $product->get_sku();

          $link = '<a rel="nofollow" href="?add-to-cart=' . $product_id . '" data-quantity="1" data-product_id="' . $product_id . '" data-product_sku="' . $product_sku . '" class="button product_type_simple add_to_cart_button ajax_add_to_cart add-to-cart" aria-label="Add to cart"><em>Add to cart</em></a>';

    }

    return $link; 
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'filter_woocommerce_loop_add_to_cart_link', 10, 2 );

Upvotes: 0

Related Questions