生成CSV文件并将数据添加为新的WordPress自定义帖子

时间:2017-10-20 作者:Shaun

我有一个页面,我正在使用一个按钮从数组中循环的数据生成一个csv文件,单击后会自动通过电子邮件发送给用户。

我还希望数据通过使用wp_insert_post() 作用

到目前为止,我已经添加了这个,但我不确定它应该放在代码中的什么地方:

    wp_insert_post(array (
       \'post_type\' => \'saved-orders\',
       \'post_title\' => \'Test\',
       \'post_content\' => $allTheCarts(),
       \'post_status\' => \'publish\',
       \'comment_status\' => \'closed\',   // if you prefer
       \'ping_status\' => \'closed\',      // if you prefer
    ));
?>
谁能帮帮我吗?
function cart_items_array() { 

$carts2 = MultiCart\\get_carts();

// All the products
$allTheCarts = array();

foreach ( $carts2 as $cart_id => $cart2 ) {

     // get array of items contained in a cart ...
    $items2 = MultiCart\\get_cart( $cart_id );

    foreach ( $items2 as $item2_id => $item2 ) {
            $compProduct = array();

            $product_name = get_post($item2[\'product_id\'])->post_title; 
            $familyterms = wp_get_post_terms( $item2[\'product_id\'], \'pa_product-family\'); 
            $cat_terms = wp_get_post_terms( $item2[\'product_id\'], \'pa_product-category\'); 
            $product_sku = get_post_meta( $item2[\'product_id\'], \'_sku\', true );


            $compProduct[] = $product_sku; 

            foreach ($cat_terms as $cat_term) { $compProduct[] = $cat_term->name; };
            foreach ($familyterms as $family) { $compProduct[] = $family->name; }; 
            $compProduct[] = $product_name;
            $compProduct[] = $item2[\'quantity\'];
            $compProduct[] = $cart2[\'name\'];

            // Store the complete product info
            $allTheCarts[] = $compProduct;
    }
} 


return $allTheCarts;

}

// Create csv
function create_csv_string($data) {

  // Open temp file pointer
  if (!$fp = fopen(\'php://temp\', \'w+\')) return FALSE;

  // Loop data and write to file pointer
  foreach ($data as $line) fputcsv($fp, $line);

  $cartsdata = cart_items_array();

  foreach ($cartsdata as $cartrow) fputcsv($fp, $cartrow);

  // Place stream pointer at beginning
  rewind($fp);

  // Return the data
  return stream_get_contents($fp);

}

 if ( isset( $_POST[\'submit\'] ) ) {

function send_csv_mail ($csvData, $body, $to = \'[email protected]\', $subject = \'Test email with attachment\', $from = \'[email protected]\') {

global $post;
$user_id = get_current_user_id();

  // This will provide plenty adequate entropy
  $multipartSep = \'-----\'.md5(time()).\'-----\';

  // Arrays are much more readable
  $headers = array(
    "From: $from",
    "Reply-To: $from",
    "Content-Type: multipart/mixed; boundary=\\"$multipartSep\\""
  );

  // Make the attachment
  $attachment = chunk_split(base64_encode(create_csv_string($csvData))); 

  // Make the body of the message
  $body = "--$multipartSep\\r\\n"
        . "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\\r\\n"
        . "Content-Transfer-Encoding: 7bit\\r\\n"
        . "\\r\\n"
        . "$body\\r\\n"
        . "--$multipartSep\\r\\n"
        . "Content-Type: text/csv\\r\\n"
        . "Content-Transfer-Encoding: base64\\r\\n"
        . "Content-Disposition: attachment; filename=\\"".date(\'Y-m-d\')."-".str_replace(\' \', \'-\', strtolower(get_user_meta($user_id, "wpcf-branch-active", true)))."-file.csv\\"\\r\\n"
        . "\\r\\n"
        . "$attachment\\r\\n"
        . "--$multipartSep--";

   // Send the email, return the result
   return @mail($to, $subject, $body, implode("\\r\\n", $headers)); 

}

$array = array(
                array("Code", "Product Category", "Product Family", "Description", "Quantity", "Bay"),          
);


send_csv_mail($array, "Hello World!!!\\r\\n This is simple text email message.");
if(!send_csv_mail) {
         echo "Error"; 
}
else {
    echo "<meta http-equiv=\\"refresh\\" content=\\"0; url=./thank-you\\" />";
}

}

?> 

1 个回复
SO网友:Anson W Han

有几个选项可用于放置wp\\U insert\\U post call;这一切归结为您所展示的功能中所需操作的顺序。

如果要在编译/填充数组后立即创建帖子,并将其作为一些可呈现标记:

创建一个字符串变量并在数组中循环,以生成任何要表示数据行(表、列表等)的html标记。更新wp\\u insert\\u post函数,将post\\u内容值设置为上面创建的字符串变量

  • 如果要在数组编译/填充为逗号分隔的文本后立即创建帖子,并希望该csv文本作为帖子内容,则需要:

    更新wp\\u insert\\u post函数,将post\\u content值设置为stream\\u get\\u contents($fp)

  • 在刚刚插入的wp\\u insert\\u post函数之后,在返回调用之前,在create\\u csv\\u string函数的rewind()和return调用之间插入wp\\u insert\\u post函数
  • 如果您在电子邮件发送之前不想插入帖子:

    您可能希望更改/分解功能,使其不会从一个函数直接传递到另一个函数,并定义表示数据处理每个状态的变量。例如,您可能在任何函数之外、函数声明之后有以下变量:

    $rawCartDataArray = cart_items_array();

    $htmlRenderableCartData = your_new_format_array_data_into_markup_function($rawCartDataArray);

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

  • 在这样分解数据后,将$附件变量定义更新为:

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

    在send\\u csv\\u mail函数末尾附近或调用send\\u csv\\u mail后在主php外部添加wp\\u insert\\u post()调用。

    另一个建议是在代码末尾移动/修改if/else,作为send\\u csv\\u mail函数本身的一种尝试。

  • 结束