Woocommerce: how to quickly and correctly get the total amount of sales for each taxonomy?

The site has a taxonomy: my_taxonomy. I need to get the total amount of sales for each custom product taxonomy, list for level 1 and for level 2, I mean it: Level0 -level1 <-- this --level2 <-- this ---level3 --level2 <-- this -level1 <-- this --level2 <-- this ---level3 ---level3 I did it like this: function handle_csv_export() { if (! wp_verify_nonce($_POST['_wpnonce'], 'generate-csv')) { return; } $orders = wc_get_orders(array( 'limit' => -1, 'status' => array('completed', 'processing', 'on-hold') )); $levels1 = $levels2 = array(); foreach (get_terms('my_taxonomy', array('hide_empty' => false, 'parent' => 0)) as $parent_term) { foreach (get_terms('my_taxonomy', array('hide_empty' => false, 'parent' => $parent_term->term_id)) as $child_term) { $levels1[] = array("value" => $child_term->term_id, "label" => $child_term->name); //get level1 foreach (get_terms('my_taxonomy', array('hide_empty' => false, 'parent' => $child_term->term_id)) as $third_term) { $levels2[] = array("value" => $third_term->term_id, "label" => $third_term->name); //get level2 } } } $level1_amount_result = $level2_amount_result = array(); foreach ($orders as $order) { $items = $order->get_items(); foreach ($items as $item) { $product_id = $item->get_product_id(); foreach ($levels1 as $level1) { if (has_term($level1['value'], 'my_taxonomy', $product_id)) { $level1_amount_result[$level1['label']] += $item->get_total(); //adding up the price for each taxonomy } } foreach ($levels2 as $level2) { if (has_term($level2['value'], 'my_taxonomy', $product_id)) { $level2_amount_result[$level2['label']] += $item->get_total(); } } } } // add to csv $filetime = time(); $list = array( array("levels1"), ); foreach ($level1_amount_result as $level1_name => $level1_amount) { array_push($list, array($level1_name, $level1_amount . '$')); } array_push($list, array("levels2")); foreach ($level2_amount_result as $level2_name => $level2_amount) { array_push($list, array($level2_name, $level2_amount . '$')); } $upload_dir = wp_upload_dir(); $file_path = $upload_dir['basedir'] . '/myorders/myorders' . $filetime . '.csv'; $folder_path = $upload_dir['basedir'] . '/myorders'; if (!file_exists($folder_path)) { mkdir($folder_path, 0777); } $files = glob($folder_path . '/*'); foreach ($files as $file) { if (is_file($file)) { unlink($file); } } header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="export.csv"'); $file = fopen($file_path, "w"); foreach ($list as $line) { fputcsv($file, $line); } readfile($file_path); fclose($file); exit; } https://prnt.sc/BEvAcv34kgqZ It seems to work with a small number of orders, but the site has many values in the taxonomy and many orders, the code takes a long time to execute and the site crashes. How can I speed up this process? Thanks.

Comment (0)

You’ll be in good company