header blog

Count Variation Sales (Shortcode)

We have previously learned how to display the number of sales for a specific product ID using a shortcode. However, this method does not work for variation IDs in WooCommerce, as WooCommerce only tracks sales for the parent product.

To address this issue, we will implement a different solution. One approach is to query the orders containing a specific variation ID and calculate the total sales from these orders. Alternatively, we can install a code snippet to begin tracking variation sales going forward, eliminating the need for manual querying and calculation.

In this case, we will explore the latter option. By implementing this snippet, we can accurately count variation sales from the moment it is installed. We will then create a shortcode to display this sales count anywhere, including within variation descriptions.

Here’s the two-part snippet: the first part hooks into WooCommerce’s sales recording to track each variation separately, and the second part registers a shortcode to display that count anywhere on your site.

add_action( 'woocommerce_recorded_sales', 'fixelar_maybe_update_variation_sales' );

function fixelar_maybe_update_variation_sales( $order_id ) {
   $order = wc_get_order( $order_id );
   if ( ! $order ) return;
   if ( count( $order->get_items() ) > 0 ) {
      foreach ( $order->get_items() as $item ) {
         if ( 'product_variation' === get_post_type( $item->get_variation_id() ) ) {
            $variation_id = $item->get_variation_id();
            $total_sales = get_post_meta( $variation_id, '_total_sales', true ) ? get_post_meta( $variation_id, '_total_sales', true ) : 0;
            update_post_meta( $variation_id, '_total_sales', $total_sales + absint( $item->get_quantity() ) );
         }
      }
   }
}

// PART 2: variation sales shortcode
// usage: [var_sales id="123"]

add_shortcode( 'var_sales', 'fixelar_sales_by_variation_id' );

function fixelar_sales_by_variation_id( $atts ) {
   $atts = shortcode_atts( array( 'id' => 0 ), $atts );
   return get_post_meta( $atts['id'], '_total_sales', true ) ? get_post_meta( $atts['id'], '_total_sales', true ) : 0;
}

Keep in mind this only counts sales going forward from the moment the snippet is installed. It doesn’t retroactively calculate variation sales from past orders, since WooCommerce didn’t track that data at the variation level before.