<?php

add_action( 'woocommerce_loaded', 'get_total_order_fees_for_year' );

function get_total_order_fees_for_year( $year ) {
	// Set up the API endpoint and keys
	$endpoint = 'https://northstarhomestead.com/wp-json/wc/v3/orders';
	$key = 'ck_a97da3e7000068e7f02dc9fcfb955f558102e3aa';
	$secret = 'cs_6c758f17f486597af782b56a20c40a5c4cb832f9';

	// Set up the API request with authentication headers
	$request_args = array(
		'method' => 'GET',
		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( $key . ':' . $secret )
		),
		'query' => array(
			'per_page' => 100,
			'page' => 1,
			'after' => $year . '-01-01T00:00:00Z',
			'before' => $year . '-12-31T23:59:59Z',
			'status' => 'any',
			'calc_taxes' => 'true',
			'calc_line_items' => 'true',
			'calc_shipping' => 'true',
			'calc_total' => 'true'
		)
	);

	// Use the `wp_loaded` action hook to ensure that WooCommerce is fully loaded
	add_action( 'wp_loaded', function() use ( $endpoint, $request_args, &$total_fees ) {
		$response = wp_safe_remote_request( $endpoint, $request_args );

		// Check if the request was successful
		if ( is_wp_error( $response ) ) {
			return $response->get_error_message();
		}

		// Decode the response body and initialize the total fees to zero
		$orders = json_decode( wp_remote_retrieve_body( $response ), true );
		$total_fees = 0;

		// Loop through the orders to calculate the total fees for the specified year
		foreach ( $orders as $order ) {
			// Use `wc_get_order()` to get the order object
			$order_obj = wc_get_order( $order['id'] );

			// Add up the fees for each order
			$total_fees += $order_obj->get_total_fee();
		}
	} );

	// Return the total fees in US dollars for the specified year
	return $total_fees;
}
Login