纯代码实现woocommerce产品页面添加buy now立即购买按钮

众所周知woocommerce的产品页面只有add to cart添加购物车的功能,但是Buy now立即购买的按钮是没有的,本文就是通过纯代码的方式实现添加Buy now立即购买按钮的功能。

温馨提示:

文中的方法还没有尽善尽美,两段代码都还存在bug,这些天也翻了不少资料都没能完美解决这个问题,没想到一个小小的按钮竟然让网上不少人都没有办法。后续找到完美方法会持续更新。

第一种方法,直接上代码

function add_content_after_addtocart() {
    // get the current post/product ID
    $current_product_id = get_the_ID();
    // get the product based on the ID
    $product = wc_get_product( $current_product_id );
    // get the "Checkout Page" URL
    $checkout_url = WC()->cart->get_checkout_url();
    // run only on simple products
    if( $product->is_type( 'simple' ) ){
?>
  <script>
    jQuery(function($)){
    <?php /* if our custom button is clicked, append the string "&quantity=", and also the quantitiy number to the URL */ ?>

        // if our custom button is clicked
        $(".custom-checkout-btn").on("click", function() {

            // get the value of the "href" attribute 
            $(this).attr("href", function() {
                // return the "href" value + the string "&quantity=" + the current selected quantity number
                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 now</a>';
			
    }
}
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );

该段代码缺陷是,每次点击Buy now按钮都只能添加一个产品到结算页面,更换代码依然不能修复问题。

第二种方法代码

function wpcoderpro_direct_checkout_button() {
global $product;
$id = $product->get_id();
if( $product->is_type( 'variable' ) ){
echo '
<script>
jQuery(document).ready(function($){
$(".redirect_to_checkout").click(function(){
$("button.single_add_to_cart_button ").click();
window.location.href="/checkout/";
});
});
</script>
<div class="button alt redirect_to_checkout" style="cursor:pointer;">Buy now</div>
';
}
elseif( $product->is_type( 'simple' ) ){
echo '
<script>
jQuery(document).ready(function($){
$(".input-text.qty").change(function(){
$(".redirect_to_checkout a").attr("href", "/checkout/?add-to-cart='. $id .'" + "&quantity= " + $(this).val());
});
});
</script>
<div class="button alt redirect_to_checkout" style="cursor:pointer;"><a href="/checkout/?add-to-cart='. $id .'">Buy now</a></div>
';
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'wpcoderpro_direct_checkout_button',1);

这段代码缺陷是,每次点击Buy now,会把放在购物车的所有产品都结算,并且最大问题是,结算的数量是选项数量的双倍。

持续更新中……

评分 post
奥博说 版权所有丨如未注明 均为原创
转载请注明:https://www.oppblog.com/archives/458

发表评论