[英]Woocommerce - On page load, add product to cart and proceed to Checkout automatically
我想给一个链接,一个允许他们使用购物车中已有产品的用户直接进入结帐页面的链接。
我相信我将需要做两件事:
我每个都有两个摘要,但是我不确定它们是否可以像这样一起工作,而且我不确定如何在特定页面上使用它 (可能只是空白页面,其显示时间不足以添加到购物车和将用户发送到结帐页面)
<?php
/*
* goes in theme functions.php or a custom plugin
**/
// add item to cart on visit
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 21;
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if {( $_product->id == $product_id )
$found = true;}
}
// if product not found, add it
if {( ! $found )
WC()->cart->add_to_cart( $product_id );}
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
/**
* Redirect users after add to cart.
*/
function my_custom_add_to_cart_redirect( $url ) {
$url = WC()->cart->get_checkout_url();
// $url = wc_get_checkout_url(); // since WC 2.5.0
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
如果也有更好的方法可以做到这一点,请告诉我。
谢谢,布莱恩
您实际上可以执行此操作,而无需任何其他代码。
WooCommerce支持通过?add-to-cart
URL参数将商品?add-to-cart
。
如果您将某人发送到任何页面,后跟URL参数?add-to-cart=21
,它将自动将ID 21的产品添加到他们的购物车中。 在这种情况下,您可以将它们直接发送到Checkout页面。
这是您的自定义URL的样子:
http://example.com/checkout/?add-to-cart=21
这种方式比运行脚本然后重定向到结帐要快得多。
我建议针对一般用例设置此功能,例如,将用户发送到example.com?get=21
,其中21
是要在加载时添加到购物车的产品ID。 要遵循这种方法,您的代码将类似于
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() && isset( $_GET['get'] ) ) {
$product_id = $_GET['get'];
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id ) {
$found = true;
}
}
// if product not found, add it
if ( ! $found ){
WC()->cart->add_to_cart( $product_id );
}
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
// Redirect users to checkout after add to cart
wp_redirect( wc_get_checkout_url() );
exit;
}
}
您不需要'woocommerce_add_to_cart_redirect'过滤器,它就可以起作用。
现在,如果您只想在特定页面上触发此事件,则说该页面的ID为55
,则该行
if ( ! is_admin() && isset( $_GET['get'] ) ) {
会变成
if ( ! is_admin() && is_page( 55 ) ) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.