0

hello everyone I have been trying to use the wc_create_order (); function in woocommerce to create an order it works, but its creating more than one order.

enter image description here I tried a fresh install of WordPress with only the woocommerce plugin but the same issue how can I create only one order

the code i used:

   $productID=104;
My_create_order($productID);





 function My_create_order($productID) {


  global $woocommerce;

  $order = wc_create_order();

  $order->add_product( get_product( $productID), 1 ); 

  $order->calculate_totals();


}

add_action( 'init', 'My_create_order' );

and something else I noticed when I add a product to an existing order like this

$myProduct = new WC_Product(104);

$order->add_product($myProduct, 1);
$order->calculate_totals();

it's also adding the product multiple times!!

enter image description here

also tried using a different way

$order_data = array(
    'post_name'     => 'order-test' ,
    'post_type'     => 'shop_order',
    'post_title'    => 'order-tests ', 
    'post_status'   => 'wc-completed',
    'ping_status'   => 'closed',    

);

// create order
$order_id = wp_insert_post( $order_data, true );

and like this

    if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {

$order=My_create_order();


}


add_action('init', 'My_create_order');



 function My_create_order() {


  global $woocommerce;

  $order = wc_create_order();



return $order;
}

but the same issue

enter image description here

6
  • edit the question to show all the code you tried and all results of debugging.
    – mmm
    Jul 22, 2018 at 9:07
  • init is fired on every HTTP request and this include AJAX calls. on which conditions do you wan to create this order ?
    – mmm
    Jul 22, 2018 at 9:30
  • i created a simple form for the user when he submit it i want to add the order
    – nweby
    Jul 22, 2018 at 9:40
  • then you have to test if the submit button of the form is submitted like if (isset($_POST["buttonName"])) { // create order ...}
    – mmm
    Jul 22, 2018 at 10:11
  • same issue the order is added more than one time if (isset($_POST["myBtn"]){ $order=My_create_order(); }
    – nweby
    Jul 22, 2018 at 10:18

1 Answer 1

1

thank you mmm it worked i just missed an ``

    if (isset($_POST["myBtn"])) 

      {  $order=My_create_order();

      }

<?php
add_action('init', 'My_create_order');



 function My_create_order() {


  global $woocommerce;

  $order = wc_create_order();



return $order;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.