【发布时间】:2018-01-26 04:41:11
【问题描述】:
我想给一个人提供一个链接,让他们可以直接登陆结帐页面,并且产品已经在他们的购物车中。
我相信我需要做两件事:
- 在页面加载时,运行脚本以自动将产品添加到购物车
- 在将产品添加到购物车时,运行另一个脚本将用户发送到结帐页面
我每个都有两个 sn-ps,但我不确定它们是否会像这样一起工作,我不确定如何让它在特定页面上工作(可能只是一个空白页面几乎不会显示足够长的时间以添加到购物车并将用户发送到结帐页面)
<?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' );
如果还有更好的方法可以做到这一点,请告诉我。
谢谢, 布赖恩
【问题讨论】:
标签: php wordpress woocommerce