Wordpress/Woocommerce相关问题。
我想在添加某个类别的物品后,通过编程将“免费礼物”添加到购物车中。这种免费礼物实际上也是一种他们可以单独从商店购买的产品,但当它与上述类别的商品组合时,将作为免费礼物。
到目前为止,我有一个工作代码,一旦添加了特定类别的项目,就可以添加额外的产品。但我不知道如何在购物车中将此商品的价格设置为零。
/*
* Automatically adding the product to the cart.
*/
function aaptc_add_product_to_cart( $item_key, $product_id ) {
$product_category_id = 92; // set category id
$product_cats_ids = wc_get_product_term_ids( $product_id, \'product_cat\' );
if ( ! is_admin() && in_array( $product_category_id, $product_cats_ids ) ) {
$free_product_id = 7506; // Product Id of the free product which will get added to cart
$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->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
function return_custom_price($price, $product) {
$myPrice = 0;
global $current_user;
$price = $myPrice;
$post_id = $post->$free_product_id;
return $price;
}
add_filter(\'woocommerce_get_price\', \'return_custom_price\', 10, 2);
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
function return_custom_price($price, $product) {
$myPrice = 0;
global $current_user;
$price = $myPrice;
$post_id = $post->$free_product_id;
return $price;
}
add_filter(\'woocommerce_get_price\', \'return_custom_price\', 10, 2);
}
}
}
add_action( \'woocommerce_add_to_cart\', \'aaptc_add_product_to_cart\', 10, 2 );
我很确定代码片段的以下部分在编程上是错误的,但我不确定如何实现免费添加产品的零价格。
function return_custom_price($price, $product) {
$myPrice = 0;
global $current_user;
$price = $myPrice;
$post_id = $post->$free_product_id;
return $price;
}
add_filter(\'woocommerce_get_price\', \'return_custom_price\', 10, 2);