Additional Woocommerce product Add To Cart button

2019-07-23 03:51发布

问题:

I need the customer to be able to choose between add to cart and continue to shop and add to cart and get re-directed to the checkout. In other words, I'm adding a extra button to the product page.

Being new to WooCommerce, I'm struggling getting the qty input to function. It works fine if buying just one, but not when adding more than one (qty).

Also, I'm failing to understand how to add support for variable products, but that might be a separate question? (sorry if so).

Here's the code I'm using:

add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );
function add_content_after_addtocart() {
    $current_product_id = get_the_ID();
    $product = wc_get_product( $current_product_id );
    $checkout_url = WC()->cart->get_checkout_url();
    if( $product->is_type( 'simple' )) { ?>
        <script>
        jQuery(function($) {
            $(".custom-checkout-btn").on("click", function() {
                $(this).attr("href", function() {
                    return this.href + '&quantity=' + $('input.qty').val();
                });
            });
        });
        </script>
        <?php
        echo '<a href="'.$checkout_url.'?add-to-cart='.$current_product_id.'" class="single_add_to_cart_button button alt">Buy &amp; Checkout</a>';
    } 
}

Any input on where I'm going wrong? All the help I can get is appreciated.

回答1:

There are some mistakes in your code… Try the following:

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
    global $product;

    $addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
    $button_class  = 'single_add_to_cart_button button alt custom-checkout-btn';
    $button_text   = __("Buy &amp; Checkout", "woocommerce");

    if( $product->is_type( 'simple' )) :
    ?>
    <script>
    jQuery(function($) {
        var url    = '<?php echo $addtocart_url; ?>',
            qty    = 'input.qty',
            button = 'a.custom-checkout-btn';

        // On input/change quantity event
        $(qty).on('input change', function() {
            $(button).attr('href', url + '&quantity=' + $(this).val() );
        });
    });
    </script>
    <?php
    echo '<a href="'.$addtocart_url.'" class="'.$button_class.'">'.$button_text.'</a>';
    endif;
}

Code goes in function.php file of your active child theme (or active theme). It should works.