十年专注,只做WordPress定制开发一件事

如何给Woocommerce添加立即购买按钮?

王超
2023-04-05
Woocommerce开发
1,521 次

我们知道Woocommerce默认的只有一个加入购物车的按钮,不太符合我们国人的使用习惯,我们一般还想加一个立即购买的按钮,点击后会跳过购物车直接到达结账页面,要实现这个功能,有现成的插件可以用,但是基于能不用插件就不用插件的原则,我们还是建议使用代码的方式来实现这个功能,而且代码实现起来也并不复杂。

1、给产品详情页添加立即购买按钮

您可以把下面的代码放到您的functions.php文件中,从而为产品详情页加入购物车旁边添加一个立即购买的按钮。

//添加立即购买按钮
add_action( 'woocommerce_after_add_to_cart_button', 'add_buy_now_button' );
function add_buy_now_button() {
    global $product;

    // Check if the product is variable and if it has enough attributes selected to display the price
    if ( $product->is_type( 'variable' ) ) {
        $variation_ids = $product->get_children();
        $variation_count = 0;
        foreach ( $variation_ids as $variation_id ) {
            $variation = wc_get_product( $variation_id );
            if ( $variation->is_in_stock() && $variation->has_attributes() && $variation->get_price() !== '' ) {
                $variation_count++;
            }
        }

        // Check if the product has a default variation set and if it has attributes selected
        if ( $product->get_default_attributes() && $product->has_attributes() ) {
            $need_selected = '';
        } else {
            $need_selected = ' disabled';
        }
    }

    // Display the "Buy Now" button
    echo '<button type="submit" name="add-to-cart" value="' . get_the_ID(). '" class="single_buy_now button alt'.$need_selected.'" id="buy_now_button" ' . ($product->is_purchasable() && $product->is_in_stock() ? '' : ' disabled') . '><i class="iconfont icon-purse1S"></i>' . __('Quick Purchase', 'woocommerce') . '</button><input type="hidden" name="is_buy_now" id="is_buy_now" value="0">';
}

注意以下,里面立即购买按钮的html部分有一个icon的字体图标,你们可以换成你们自己的。

2、为立即购买按钮添加重定向

//立即购买重定向
add_filter('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($redirect_url) {
  if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) {
     global $woocommerce;
     $redirect_url = wc_get_checkout_url();
  }
  return $redirect_url;
}

3、将下面的js代码放到footer.php或者您的js文件中

// listen if someone clicks 'Buy Now' button
    $('#buy_now_button').click(function(){
        // set value to 1
        $('#is_buy_now').val('1');
        //submit the form
        $('form.cart').submit();
    });

以上就是使用代码为woocommerce添加立即购买按钮的方法,希望对大家有所帮助!

文章标签:

WordPress日记主要承接WordPress主题定制开发PSD转WordPressWordPress仿站以及以WordPress为管理后端的小程序、APP,我们一直秉持“做一个项目,交一个朋友”的理念,希望您是我们下一个朋友。如果您有WordPress主题开发需求,可随时联系QQ:919985494 微信:18539976310

搜索

嘿,有问题找我来帮您!