Additional Woocommerce product Add To Cart button that redirect to checkout

一曲冷凌霜 提交于 2019-12-24 11:11:41

问题


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.



来源:https://stackoverflow.com/questions/54857872/additional-woocommerce-product-add-to-cart-button-that-redirect-to-checkout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!