创建产品后如何将产品添加到购物车

时间:2021-07-18 23:48:24

标签: php wordpress woocommerce product cart

我需要使用代码创建 woocommerce 产品,我正在使用此代码创建产品。

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 );

}

代码运行正常,产品已创建并保存在 woocommerce 中,问题是产品创建完成后,我必须将其添加到购物车中,因为我正在使用此代码。

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

然而,即使您成功添加到 woocommerce 的产品未能添加到购物车,它也会向我返回此错误。

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

由于我可以正确地将产品添加到购物车中,我认为问题是元字段仍在更新中,但我不知道如何使该功能等待产品完成更新才能添加到购物车。

希望得到任何帮助,谢谢

0 个答案:

没有答案