Generate CSV file and add data as a new wordpress custom post

There’s a few options for where to put your wp_insert_post call; it all boils down to order of desired operations within the functionality as you’ve presented it.

  • If you want to create the post as soon as the array has been compiled/populated, and as some renderable markup:

    1. create a string variable and loop through the array to generate whatever html markup you want to represent the rows of data (table, list, etc)
    2. update your wp_insert_post function to set the post_content value to your string variable created above.
    3. insert the wp_insert_post function just before your return statement in the
      cart_items_array() function.
  • If you want to create the post as soon as the array has been compiled/populated into the comma separated text and want that csv text as the post content, you’ll want to:

    1. update your wp_insert_post function to set the post_content value to stream_get_contents($fp);
    2. insert the wp_insert_post function just between your rewind() and return calls in the create_csv_string function
    3. after the wp_insert_post function you just inserted, and before the return call, add a call to rewind the file’s stream pointer again.
  • If you don’t want to insert the post until after the email has been sent:

    1. you’ll probably want to change/break up your functionality so that it doesn’t pipe from one function directly into another, as well as define variables representing each state of processing for the data. for example you might have the following variables outside of any functions, and after the function declarations:

      $rawCartDataArray = cart_items_array();

      $htmlRenderableCartData = your_new_format_array_data_into_markup_function($rawCartDataArray);

      $csvCartData = create_csv_with_header_row_function($csvDataHeaders, $rawCartDataArray);

    2. After breaking out the data like this, update $attachment variable definition to:

      $attachment = chunk_split(base64_encode($csvCartData));

    3. update your wp_insert_post function to set the post_content value to either the $htmlRenderableCartData or $csvCartData;

    4. Add a wp_insert_post() call either near the end of your send_csv_mail function, or outside in the main php after your call to send_csv_mail.

Another recommendation would be to move/rework your if/else at the end of the code as a try/catch in the send_csv_mail function itself.