php – How to add a product to the cart after it is created


I need to create a woocommerce product with code, I am using this code to create the product.

function createNewProductTest() {

  $post_id = wp_insert_post( array(
  'post_title' => 'Custom Suscription',
  'post_content' => 'Text',
  'post_status' => 'publish',
  'post_type' => "product",
  ) );

  wp_set_object_terms( $post_id, 'subscription', 'product_type' );
  update_post_meta( $post_id, '_price', '600' );
  update_post_meta( $post_id, '_subscription_price', '600' );
  update_post_meta( $post_id, '_subscription_period', 'year' );
  update_post_meta( $post_id, '_subscription_length', '1' );

  $woocommerce->cart->add_to_cart( $post_id );


The code works correctly, the product is created and saved in woocommerce, the problem is that once the product is finished being created I must add it to the cart, for that I am using this code.

$woocommerce->cart->add_to_cart( $post_id );

However even though the product that you successfully add to woocommerce fails to add to cart, it returns this error to me.

Product has been removed from your cart because it has since been modified.

As I can add the product to the cart correctly, I think the problem is that the meta fields are still being updated, but I don’t know how to make the function wait for the product to finish updating to be added to the cart.

I would appreciate any help, Thank you

Jefferzon Bol 4 months 2021-07-18T19:36:01-05:00 0 Answers 0 views 0

Leave an answer