NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Intermediate
Last modified : Oct 29 2023
Estimated reading time : 2 minutes, 26 seconds - 90 words
Share the post "Calculating Average Shipping Cost per Order – WooCommerce"
With this tutorial, we will calculate the average shipping cost per order across all orders; including those with no shipping fees. You can tweak the function like this:
Calculating the average order shipping cost for all orders
function woocl_calculate_average_shipping_cost_per_order_all_orders() {
$args = array(
'status' => array('wc-completed', 'wc-shipped'),
'limit' => -1,
'return' => 'ids',
);
$shipped_orders = wc_get_orders($args);
$total_shipping_cost = 0;
$total_orders = count($shipped_orders);
foreach ($shipped_orders as $order_id) {
$order = wc_get_order($order_id);
$shipping_total = (float) $order->get_shipping_total();
$total_shipping_cost += $shipping_total;
}
if ($total_orders > 0) {
$average_shipping_cost_per_order = $total_shipping_cost / $total_orders;
} else {
$average_shipping_cost_per_order = 0;
}
return $average_shipping_cost_per_order;
}
Let’s now display it in our template.
$average_shipping_cost_per_order = woocl_calculate_average_shipping_cost_per_order_all_orders(); echo 'Coût moyen d\'expédition par commande (toutes les commandes): ' . wc_price($average_shipping_cost_per_order);
Calculating the average order shipping cost: Order with shipping fees
If you want to calculate average order shipping costs for orders with a shipping value, you can use the following function:
function woocl_calculate_average_shipping_cost_for_orders_with_shipping() {
$args = array(
'status' => array('wc-completed', 'wc-shipped'),
'limit' => -1,
'return' => 'ids',
);
$shipped_orders = wc_get_orders($args);
$total_shipping_cost = 0;
$orders_with_shipping = 0;
foreach ($shipped_orders as $order_id) {
$order = wc_get_order($order_id);
$shipping_total = (float) $order->get_shipping_total();
if ($shipping_total > 0) {
$total_shipping_cost += $shipping_total;
$orders_with_shipping++;
}
}
if ($orders_with_shipping > 0) {
$average_shipping_cost = $total_shipping_cost / $orders_with_shipping;
} else {
$average_shipping_cost = 0;
}
return $average_shipping_cost;
}
Displaying average order shipping cost (only for orders with a shipping value)
$average_shipping_cost = woocl_calculate_average_shipping_cost_for_orders_with_shipping(); echo 'Coût moyen d\'expédition (uniquement les commandes avec frais d\'expédition): ' . wc_price($average_shipping_cost);