WooCommerce Average Category Price Based On Products

Looking to get the average category price based on the products inside the WooCommerce category? All you may need is to query the post meta table.

Get the average category price

To get the average category price, you need to query all the categories and their products as per below.

global $wpdb;
$args = array(
'taxonomy' => 'product_cat',
'posts_per_page' => -1,
'hide_empty' => 0,
'orderby' => 'title',
'order' => 'ASC',
);
foreach ( get_categories( $args ) as $category ) :
$post_ids = get_posts( array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category->term_id,
),
),
'fields' => 'ids',
) );

$product_prices = 0;
$product_count = 0;

foreach ( $post_ids as $pId ) :
$price = $wpdb->get_var("SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_price' AND post_id = $pId");
$product_prices += $price;
$product_count++;
endforeach;

$average_product_price = number_format( $product_prices/$product_count, 1 );
echo $average_product_price;
endforeach;