简体   繁体   中英

Woocommerce multiple products to cart not working?

I am having problem with adding multiuple custom products to woocommerce cart. How to add the multiple products to cart programatically. Please check with my below code and advise on this. I am having this code in custom page which is template folder.

$values = array();
         $post_values = array();
         $i=0;
    foreach($_POST['post_quantity'] as $key =>$value){


   /*$lastid[$i] = multiple product inserted id's */


$wpdb->insert('wp_posts', array(
      'post_title'    => 'xxxxx  xxx ID: '.$_POST['quoted_sid'][$key].'  - Product ID: '.$_POST['product_id'][$key],
      'post_content'  => $_POST['product_description'][$key],
      'post_date' => date('Y-m-d H:i:s'),
      'post_status'   => 'publish',
      'post_author'   => 1,
      'post_type'     =>'product'
    ));
    $lastid[$i] = $wpdb->insert_id;

            $date[$i] = date('Y-m-d H:i:s');

        add_post_meta($lastid[$i], '_regular_price', $_POST['product_price'][$key]);
        add_post_meta($lastid[$i], '_price', $_POST['product_price'][$key]);
        add_post_meta($lastid[$i],'_visibility','visible');

    add_post_meta($lastid[$i], '_stock_status', 'instock' );
    add_post_meta($lastid[$i], '_weight', '11' );
    add_post_meta($lastid[$i], '_sku', 'Quoted xxxx_'.$_POST['product_id'][$key] );
    add_post_meta($lastid[$i], '_duplicate_price', $_POST['product_duplicate_price'][$key] );
    add_post_meta($lastid[$i], '_material', $_POST['product_material'][$key] );

$i++;
        //$woocommerce->cart->add_to_cart(  $lastid[$i], $quantity=$_POST['post_quantity'][$key], $cart_item_data ); 

    }

    $woocommerce->cart->add_to_cart(  $lastid[$i], 
        $quantity=$_POST['post_quantity'][$key], $cart_item_data ); 

I tried like this the below function is working but i am not sure how to add quanity and other cart_item_data_fields

$product_ids = filter_var_array( $lastid, FILTER_SANITIZE_SPECIAL_CHARS );
        foreach ( $product_ids as $product_id ) {
            $woocommerce->cart->add_to_cart( $product_id );
        } 

How to pass the quantity and other cart_item_data fields.

You are passing the value of the variable assignment of quantity in the function invocation. So the value is just false if the assignment result returns false. You need to either pass in a pre-assigned variable or the actual expression value.

(When you are declaring function definition, you can assign function arguments to "constant" values for defaults.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM