我已经广泛搜索了一个解决方案,当有人输入我制作的隐藏产品优惠券时,将免费项目(我用woocommerce隐藏了)添加到购物车中。这是我正在使用的代码,它是这个的修改版本:http://docs.woothemes.com/document/auto-add-product-to-cart-on-visit/。不同之处在于,我尝试使用应用的优惠券,而不是使用购物车总数来添加它。
这是我当前的代码,它没有将产品添加到购物车:
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 1211;
$found = false;
$coupon_id = 1212;
if( $woocommerce->cart->applied_coupons == $coupon_id ) {
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->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 )
$woocommerce->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
我很确定错误发生在这里'( $woocommerce->cart->applied_coupons == $coupon_id )',但我不知道正确的标识符。
这是我的职能.php
谁能帮我?谢谢
我遇到类似的情况,并使用了您的一些代码并进行了一些调整。 这对我有用:if(in_array($coupon_id, $woocommerce->cart->applied_coupons)){
干杯!
我知道
这是古老的,但我有基本相同的需求。所以我想我会继续发布我的解决方案。我几乎不是这方面的专家,所以我相信还有很大的改进空间。我把它放在我的函数中.php(显然从这里的原始帖子中借用了很多):
function mysite_add_to_cart_shortcode($params) {
// default parameters
extract(shortcode_atts(array(
'prod_id' => '',
'sku' => '',
), $params));
if( $sku && !$prod_id ) $prod_id = wc_get_product_id_by_sku($sku);
if($prod_id) {
$cart_contents = WC()->cart->get_cart_contents();
if ( sizeof( $cart_contents ) > 0 ) {
foreach ( $cart_contents as $values ) {
$cart_prod = $values['product_id'];
if ( $cart_prod == $prod_id ) $found = true;
}
// if product not found, add it
if ( ! $found ) WC()->cart->add_to_cart( $prod_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $prod_id );
}
}
return '';
}
add_shortcode('mysite_add_to_cart','mysite_add_to_cart_shortcode');
add_action( 'woocommerce_applied_coupon', 'mysite_add_product' );
function mysite_add_product($coupon_code) {
$current_coupon = new WC_Coupon( $coupon_code );
$coupon_description = $current_coupon->get_description();
do_shortcode($coupon_description);
return $coupon_code;
}
这使我可以在优惠券描述中添加一个简码,指定在应用优惠券时应添加的产品。它可以是 [mysite_add_to_cart prod_id=1234] 或 [mysite_add_to_cart sku=3456]。到目前为止,它似乎工作正常。