php - Woocommerce - 单击添加到购物车时同时添加插件产品和产品
问题描述
我正在开发一个 Woocommerce 项目,当用户单击“添加到购物车”按钮时,我想将插件产品和实际产品添加到购物车中,我尝试了下面的代码,但它给了我一个错误,即插件产品已用完股票。然而,该产品实际上并没有缺货。它将产品添加到购物车中,不包括附加产品。插件产品是可变产品,这可能是导致问题的原因。我很感激任何帮助。
add_action( 'woocommerce_before_add_to_cart_button', 'content_before_add_to_cart_btn' );
function content_before_add_to_cart_btn(){
echo '<h3>Purchase Your Kit Now</h3>';
echo '<div class="addon-description"><p>I understand that supplies are provided in class and because training is based on Lavish Lashes products, a kit purchase or it’s equivalent in retail products (adhesive, remover, lashes) is one of five requirements prior to receiving certification.</p>
</div>';
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'product_cat' => 'eyelash-extension-kits'
);
$loop = new WP_Query( $args );
//var_dump($loop);
?>
<select class="product-select" name="assessories">
<option>Select an option...</option>
<option>In Class Kit Provided (Free) </option>
<?php
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$product = wc_get_product();
$id = $product->get_id();
$price = get_post_meta( get_the_ID(), '_price', true ); ?>
<p><?php $priceTag = wc_price( $price ); ?></p>
<option value='<?php echo $id; ?>'> <?php
echo get_the_title(); ?> <?php echo $priceTag; ?>
</option>
<?php
endwhile; ?>
</select>
<?php
wp_reset_query();
}
add_action('woocommerce_add_to_cart', 'custome_add_to_cart');
function custome_add_to_cart() {
global $woocommerce;
$product_id = $_POST['assessories'];
$arr = array();
$arr['attribute_adhesive-selection'] = 'Elite Bond $0.00';
$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, $arr, null );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id, $arr, null );
}
}
谢谢!
解决方案
推荐阅读
- python - Pandas 中的额外条形图?
- php - 如果出现多个连字符,则从路由中获取变量
- python - Python:pandas groupby 到基于索引的字典
- c# - 使用 CsvHelper 从 CSV 文件中获取单元格值的问题
- php - 哪里没有工作
- java - 删除每个单词末尾的字母“e” Java
- c# - 如果权限在集合 A 中,如果不在集合 B 中,如何使用 LINQ 搜索权限
- curl - 在 curl 中使用 --local-port 选项时在 tcpdump 中获取不同的本地端口值
- sql - 在 Oracle 中生成具有 2 个日期之间时间间隔的行
- javascript - 加载器 div 中的 ASP.net GIF 即使正确调用也不播放