我试图为woocommerce订单创建一个自定义导出到CSV。代码到目前为止还可以工作,但是打印的csv文件看起来很奇怪。整个页面的html都打印在csv文件中,所需的循环/表格只出现在底部。看一下表格,似乎条目也是加倍的-就像订单ID 1558连续出现两次,这对所有条目重复。我花了几个小时在这里寻找解决方案,特别是在csv文件中删除html。大多数解决方案建议我把头函数放在顶部,其他人建议我从代码中删除html。我已经尝试了所有这些,但似乎仍然缺少一些东西。我使用elementor,并在前端创建了一个html按钮。我现在试图使用这个按钮来调用csv文件下载。请帮助。
function orderscsvdownload(){
if (isset( $_POST['export'] ) ) {// when button on the page is clicked
$fromdate = $_POST['fromDate'];
$todate = $_POST['toDate'];
$args = array(
'post_type' => array( 'shop_order' ),
'posts_per_page' => 30,
//'paged' => $paged,
'limit' => -1,
);
$tablecontents= wc_get_orders($args);
$fileName = "phpzag_export_".date('Ymd') . ".csv";
$file = fopen('php://output', 'w');
$header = array("Id", "Name", "Item", "Value", "Date");
fputcsv($file, $header);
foreach ($tablecontents as $content) {
$orderData = array();
$orderData[] = $content->get_id();
$orderData[] = $content->get_total();
$orderData[] = $content->get_status();
$orderData[] = $content->get_billing_first_name();
$orderData[] = $content->get_date_created();
// ob_end_clean();
fputcsv($file, $orderData);
fputcsv($file, $orderData);
}
fclose($file);
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/csv;");
exit;
}
}
add_shortcode('csvdownload','orderscsvdownload');// i had to add this shortcode on the page for the download to work. Sort of calls this function on the page for the download to work.
1条答案
按热度按时间vlf7wbxs1#
20多个小时后,生活又好了!我得到了代码工作。这不是一个专业的解决方案,但让我感到自豪,并且适用于像我这样的新手,他们正在努力 AJAX 调用,jQuery,甚至不知道如何从wpdb检索一些东西。欢迎您改进答案。
我不得不在页面上添加这个短代码来下载工作。在页面上调用这个函数来下载工作