Home » Php » php – "Add to Cart" functionality instead of "Select Options" button behavior for variable products

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

Posted by: admin February 25, 2020 Leave a comment

Questions:

Woocommerce has two button types in the product loop “add to cart” for adding simple products to cart and “select options” if a simple product becomes a variable one or a subscription option is added.

My setting: All Woocommerce products are configured as simple products and subscription products at the same time (using the “Woocommerce Subscription” and “All Products for Woocommerce Subscription” plugins). Default is set to simple product. 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.

How to&Answers:
function filter_woocommerce_loop_add_to_cart_link( $args, $product ) {

    if ( is_shop() && $product->product_type === 'simple' ) {
        $product_id = $product->get_id();
        $product_sku = $product->get_sku();
        $product_url = $product->add_to_cart_url();
        $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 );

Answer:

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