额外的“添加到购物车”按钮重定向到 WooCommerce Loop 上的结账

我需要 WooCommerce 存档上的一个按钮,将产品添加到购物车并将客户重定向到结账。我称之为“购买和结帐”。


我通过使用woocommerce_after_shop_loop_item操作连接到存档,并且我已经定义了global $product;参数。


然后,我获取产品 ID,然后定义添加到购物车 url(atc_url参数)。问题是,当单击“添加到购物车”时,未添加产品。


到目前为止,这是我的代码,我不太确定这里出了什么问题。


add_action( 'woocommerce_after_shop_loop_item', 'buy_checkout_on_archive', 20 );

function buy_checkout_on_archive(){


    global $product;


    $pid = $product->get_id();


    $atc_url = wc_get_checkout_url().'?add-to-cart='.$pid;


    $button_class = 'loop-checkout-btn';


    $button_text = __('Buy & Checkout', 'woocommerce');


        if ($product->is_type('simple')){

            echo '<a href="'.$atc_url.'" class="'.$button_class.'">'.$button_text.'</a>';

    }

}


交互式爱情
浏览 92回答 1
1回答

慕仙森

以下方法可以解决这个问题,在 WooCommerce 档案上添加一个自定义“添加到购物车”按钮,该按钮在将产品添加到购物车后重定向到结账:add_action( 'woocommerce_after_shop_loop_item', 'buy_checkout_on_archive', 20 );function buy_checkout_on_archive(){&nbsp; &nbsp; global $product;&nbsp; &nbsp; if ( $product->is_type('simple') ){&nbsp; &nbsp; &nbsp; &nbsp; $product_id&nbsp; &nbsp;= $product->get_id();&nbsp; &nbsp; &nbsp; &nbsp; $button_url&nbsp; &nbsp;= '?addtocart='.$product_id;&nbsp; &nbsp; &nbsp; &nbsp; $button_class = 'button loop-checkout-btn';&nbsp; &nbsp; &nbsp; &nbsp; $button_text&nbsp; = __('Buy &amp; Checkout', 'woocommerce');&nbsp; &nbsp; &nbsp; &nbsp; echo '<a href="'.$button_url.'" class="'.$button_class.'">'.$button_text.'</a>';&nbsp; &nbsp; }}add_action( 'template_redirect', 'addtocart_on_archives_redirect_checkout' );function addtocart_on_archives_redirect_checkout(){&nbsp; &nbsp; if( isset( $_GET['addtocart'] ) && $_GET['addtocart'] > 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; WC()->cart->add_to_cart( intval($_GET['addtocart']) );&nbsp; &nbsp; &nbsp; &nbsp; // Checkout redirection&nbsp; &nbsp; &nbsp; &nbsp; wp_safe_redirect( wc_get_checkout_url() );&nbsp; &nbsp; &nbsp; &nbsp; exit;&nbsp; &nbsp; }}代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
打开App,查看更多内容
随时随地看视频慕课网APP