首页 > 解决方案 > 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 );
    }
}

谢谢!

标签: phpwordpresswoocommercehook-woocommerce

解决方案


推荐阅读